Help on group by clause
I have a table which is defined like this.
unique_number NOT NULL VARCHAR2(64),
input_unique_number VARCHAR2(64),
source_system VARCHAR2(40),
end_system VARCHAR2(40),
type VARCHAR2(32),
date_time_sent TIMESTAMP(6),
transaction_name VARCHAR2(60)
type will have input, output and failed
For every input message a unique_number is generated it will have source_sytem value populated but not end_sytem value
For every output message a unique_number is generated plus it will have input_unique_number same as that of input message.
For every output message source_system and end_system values are populated.
I am trying to create a report which will give input, output and failed count for each end site, but output is getting the blank ids grouped for the input_messages
select
count(case type when 'input' then Unique_id end) as I,
count(case type when 'output' then Unique_id end) as O,
count(case type when 'failed' then Unique_id end ) as F,
transaction_name,
end_system
from message_table
where to_char(date_time_sent,'DD-MON-YY HH24:MI:SS') between '18-MAY-11 09%' and '19-MAY-11 11%'
and source_system='&Source_system'
group by transaction_name, end_system
ORDER BY end_system;
I got the following output
I O F TRANSACTION_Name END_SYSTEM
0 11 0 DistProdQualityEvent EANCM5051256614152
22 0 11 DistProdQualityEvent EANCM
0 1 0 DistInventoryReport EANCM5051351029368
1 0 0 DistInventoryReport EANCM
But I trying for output something like this
I O F TRANSACTION_Name END_SYSTEM
22 11 11 DistProdQualityEvent EANCM5051256614152
1 1 0 DistInventoryReport EANCM5051351029368
Can you please let me know is such an output is possible or not
Hi,
Perhaps this is what you want:
select count(case type when 'input' then Unique_id end) as I,
count(case type when 'output' then Unique_id end) as O,
count(case type when 'failed' then Unique_id end) as F,
transaction_name,
MAX (end_system) AS max_end_system -- Changed
from message_table
where date_time_sent between TO_DATE ( '18-MAY-2011 09' -- Compare DATEs, not strings
, 'DD-MON-YYYY HH24'
and TO_DATE ( '19-MAY-2011 11%'
, 'DD-MON-YYYY HH24'
and source_system = '&Source_system'
group by transaction_name -- Without end_system -- Changed
ORDER BY max_end_system -- Changed
;If you include end_system in the GROUP BY clause, then rows with end_system='EANCM5051256614152' will not be grouped with rows with end_system='EANCM'.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data. Why should the output say 'EANCM5051256614152' and not ''EANCM'?
Always say which version of Oracle you're using.
Edited by: Frank Kulash on Jun 3, 2011 8:49 AM
Similar Messages
-
Group By clause in oracle 10g help needed
Hi
we have a requirement that get the AR aging details at customer level.I have written the following query to fetch the correct rows at invoice level.But now i need to sum the amounts and i should show at invoice level and customer level.Could you please help me how can i group by customer level.
Here is the query i used
select ps.org_id
, sob.SET_OF_BOOKS_ID
, sob.CHART_OF_ACCOUNTS_ID
, gcc.SEGMENT1 Company
, gcc.SEGMENT2 Location
, gcc.SEGMENT3 Department
, gcc.SEGMENT4 Account
, gcc.SEGMENT5 Future_1
, gcc.SEGMENT6 Future_2
, gcc.SEGMENT7 Future_3
, gcc.CONCATENATED_SEGMENTS gl_cc_concat_kff
, ps.trx_number
, ps.trx_date
, ps.due_date
, ps.invoice_currency_code
, sob.currency_code SOB_Currency_Code
, ps.class
, ps.amount_due_original
, ps.amount_due_original * nvl(ps.exchange_rate, 1) acctd_amount_due_original
, ps.amount_due_remaining
, ps.acctd_amount_due_remaining
, ps.status
, ps.cust_trx_type_id
, ps.customer_site_use_id
, ps.customer_trx_id
, ps.cash_receipt_id
, ps.gl_date
, rctlda.CODE_COMBINATION_ID
, ps.customer_id
, nvl(rcta.ATTRIBUTE5,ps.CUSTOMER_ID) End_Customer_Id
, rc.customer_number
, rc2.CUSTOMER_NUMBER Brand_Cust_no
, round((sysdate-ps.due_date))
from gl_sets_of_books sob
, hr_operating_units ou
, ar_payment_schedules_all ps
, ra_customers rc
, ra_cust_trx_line_gl_dist_all rctlda
, gl_code_combinations_kfv gcc
, ra_customer_trx_all rcta
, ra_customers rc2
where sob.set_of_books_id = ou.set_of_books_id
and ou.organization_id = ps.org_id
and ps.status = 'OP'
and ps.org_id is not null
and ps.CUSTOMER_ID=rc.CUSTOMER_ID
and ps.CUSTOMER_TRX_ID=rctlda.CUSTOMER_TRX_ID
and rctlda.ACCOUNT_CLASS='REC'
and rctlda.latest_rec_flag = 'Y'
and rctlda.CODE_COMBINATION_ID=gcc.CODE_COMBINATION_ID
and ps.CUSTOMER_TRX_ID=rcta.CUSTOMER_TRX_ID
and gcc.CODE_COMBINATION_ID=39446
-and ps.trx_number = '1-15O0A8O'
--and rc.CUSTOMER_NUMBER='1-10PA5KX'
and nvl(rcta.ATTRIBUTE5,ps.CUSTOMER_ID)=rc2.CUSTOMER_ID
Could any one help me how to get the same columns with sum( ps.amount_due_original ) for each customer.I tried to use group by clause but it is again giving invoice level.
But my req is for each customer invoice amount should be summed and it should give the total
Thanks
Yif you need to have the sum of invoice related to each customer then may also need to check for the
CUBE
http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_10002.htm#sthref9448
and example here
http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_10002.htm#i2066443
and ROLLUP
http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_10002.htm#sthref9445
I couldn't follow with all your SQL statement, or I could rewrite it for you again
Thanks
Edited by: user9532576 on Jul 21, 2009 9:24 AM -
Help with correct group by clause
This 'simple' statement is driving me nuts. Can someone please give me the correct group by clause to limit my ouput so that the same task does not show up multiple times? Please Help.
CURSOR cur1 IS
select substr(a.resource_name, instr(a.resource_name, ' ', 1) +1, 99)||', '
||substr(a.resource_name, 1, instr(a.resource_name, ' ', 1) -1) employee,
c.description description,
b.hours hours,
(select sum(b.hours)
from timelogged b
where a.resource_id = b.resource_id
and b.task_id = c.task_id
and b.log_date between trunc(timelog_choosedate) and trunc (timelog_choosedate) + 6) total
from resources a,
timelogged b,
tasks c
where a.resource_id = b.resource_id
and b.task_id = c.task_id
and b.log_date between trunc(timelog_choosedate) and trunc(timelog_choosedate) + 6
--group by a.resource_name, c.description, a.resource_id, c.task_id
order by substr(a.resource_name, instr(a.resource_name, ' ', 1) +1, 99);you can try the DISTINCT
select distinct
substr(a.resource_name, instr(a.resource_name, ' ', 1) +1, 99)||', '||
substr(a.resource_name, 1, instr(a.resource_name, ' ', 1) -1) employee,
c.description description,
b.hours hours,
(select sum(b.hours)
from timelogged b
where a.resource_id = b.resource_id
and b.task_id = c.task_id
and b.log_date between trunc(timelog_choosedate) and trunc (timelog_choosedate) + 6) total
from resources a,
timelogged b,
tasks c
where a.resource_id = b.resource_id
and b.task_id = c.task_id
and b.log_date between trunc(timelog_choosedate) and trunc(timelog_choosedate) + 6but i guess the tables that your are trying to join are all detail table which would normally give you multiple result -
How to write a SQL Query without using group by clause
Hi,
Can anyone help me to find out if there is a approach to build a SQL Query without using group by clause.
Please site an example if is it so,
RegardsI hope this example could illuminate danepc on is problem.
CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
CREATE OR REPLACE FUNCTION GET_ARR return my_array
as
arr my_array;
begin
arr := my_array();
for i in 1..10 loop
arr.extend;
arr(i) := i mod 7;
end loop;
return arr;
end;
select column_value
from table(get_arr)
order by column_value;
select column_value,count(*) occurences
from table(get_arr)
group by column_value
order by column_value;And the output should be something like this:
SQL> CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
2 /
Tipo creato.
SQL>
SQL> CREATE OR REPLACE FUNCTION GET_ARR return my_array
2 as
3 arr my_array;
4 begin
5 arr := my_array();
6 for i in 1..10 loop
7 arr.extend;
8 arr(i) := i mod 7;
9 end loop;
10 return arr;
11 end;
12 /
Funzione creata.
SQL>
SQL>
SQL> select column_value
2 from table(get_arr)
3 order by column_value;
COLUMN_VALUE
0
1
1
2
2
3
3
4
5
6
Selezionate 10 righe.
SQL>
SQL> select column_value,count(*) occurences
2 from table(get_arr)
3 group by column_value
4 order by column_value;
COLUMN_VALUE OCCURENCES
0 1
1 2
2 2
3 2
4 1
5 1
6 1
Selezionate 7 righe.
SQL> Bye Alessandro -
How to use order by within Group by clause
Hi All,
I need a help as to how should i use the Order by clause so that the data should be in order with respect to one column, and at the same time whole data is grouped by some other column...like
Select RaceNo,Venue,FP,BP from Race group by RaceNo
Here I want to order by FP in ascending order for each group. When i am using it , whole order is changing.
Can anybody suggest me how to use order by clause that would apply to each group of data.
Thanks .order by clause should be used at the last in any query.......but in group by clause u can't use use that becoz u group according to column then no ordering is needed there......if u want to filter something then u can use having clause and later if u need to arrange then u can use order by clause.........
i hope this eg.l gives u some clarification....
e.g
select deptno,count(empno)
from dept
group by deptno
having count(empno) > 10
order by deptno -
Creation of view with clob column in select and group by clause.
Hi,
We are trying to migrate a view from sql server2005 to oracle 10g. It has clob column which is used in group by clause. How can the same be achived in oracle 10g.
Below is the sql statament used in creating view aling with its datatypes.
CREATE OR REPLACE FORCE VIEW "TEST" ("CONTENT_ID", "TITLE", "KEYWORDS", "CONTENT", "ISPOPUP", "CREATED", "SEARCHSTARTDATE", "SEARCHENDDATE", "HITS", "TYPE", "CREATEDBY", "UPDATED", "ISDISPLAYED", "UPDATEDBY", "AVERAGERATING", "VOTES") AS
SELECT content_ec.content_id,
content_ec.title,
content_ec.keywords,
content_ec.content content ,
content_ec.ispopup,
content_ec.created,
content_ec.searchstartdate,
content_ec.searchenddate,
COUNT(contenttracker_ec.contenttracker_id) hits,
contenttypes_ec.type,
users_ec_1.username createdby,
Backup_Latest.created updated,
Backup_Latest.isdisplayed,
users_ec_1.username updatedby,
guideratings.averagerating,
guideratings.votes
FROM users_ec users_ec_1
JOIN Backup_Latest
ON users_ec_1.USER_ID = Backup_Latest.USER_ID
RIGHT JOIN content_ec
JOIN contenttypes_ec
ON content_ec.contenttype_id = contenttypes_ec.contenttype_id
ON Backup_Latest.content_id = content_ec.content_id
LEFT JOIN guideratings
ON content_ec.content_id = guideratings.content_id
LEFT JOIN contenttracker_ec
ON content_ec.content_id = contenttracker_ec.content_id
LEFT JOIN users_ec users_ec_2
ON content_ec.user_id = users_ec_2.USER_ID
GROUP BY content_ec.content_id,
content_ec.title,
content_ec.keywords,
to_char(content_ec.content) ,
content_ec.ispopup,
content_ec.created,
content_ec.searchstartdate,
content_ec.searchenddate,
contenttypes_ec.type,
users_ec_1.username,
Backup_Latest.created,
Backup_Latest.isdisplayed,
users_ec_1.username,
guideratings.averagerating,
guideratings.votes;
Column Name Data TYpe
CONTENT_ID NUMBER(10,0)
TITLE VARCHAR2(50)
KEYWORDS VARCHAR2(100)
CONTENT CLOB
ISPOPUP NUMBER(1,0)
CREATED TIMESTAMP(6)
SEARCHSTARTDATE TIMESTAMP(6)
SEARCHENDDATE TIMESTAMP(6)
HITS NUMBER
TYPE VARCHAR2(50)
CREATEDBY VARCHAR2(20)
UPDATED TIMESTAMP(6)
ISDISPLAYED NUMBER(1,0)
UPDATEDBY VARCHAR2(20)
AVERAGERATING NUMBER
VOTES NUMBERAny help realyy appreciated.
Thanks in advance
Edited by: user512743 on Dec 10, 2008 10:46 PMHello,
Specifically, this should be asked in the
ASP.Net MVC forum on forums.asp.net.
Karl
When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
My Blog: Unlock PowerShell
My Book: Windows PowerShell 2.0 Bible
My E-mail: -join ('6F6C646B61726C40686F746D61696C2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}}) -
Hi,
Please help me in the following query.
SELECT
a.bcast_id ,
a.bcast_file_nm ,
a.clickthru_url_cd ,
a.list_id ,
a.prs_id ,
a.resp_cd ,
a.run_seq ,
COUNT(a.resp_cd) ,
c.src_grp_cd ,
b.site_cd
FROM
gca_cbx_response_test a ,
gca_program_run_hist b ,
campaign_master c
WHERE
a.list_id=b.list_id
AND
a.run_seq=b.campaign_run_seq
AND
b.campaign_cd=c.campaign_cd
GROUP BY
a.bcast_id ,
a.bcast_file_nm ,
a.clickthru_url_cd ,
a.list_id ,
a.prs_id ,
a.resp_cd ,
a.run_seq ,
c.src_grp_cd ,
b.site_cd
HAVING
a.resp_ts
BETWEEN
to_date('04-AUG-2005 00:01:32','DD-MON-YYYY HH24:MI:SS')
AND
to_date('04-AUG-2005 00:01:32','DD-MON-YYYY HH24:MI:SS');
But the following group by query is throwing error that a.resp_ts is not a group by function.
But i don't want to add a.resp_ts in group by clause.
Please help me in this query.
Thanks,
DilipHow about:
SELECT a.bcast_id ,
a.bcast_file_nm ,
a.clickthru_url_cd ,
a.list_id ,
a.prs_id ,
a.resp_cd ,
a.run_seq ,
COUNT(a.resp_cd) ,
c.src_grp_cd ,
b.site_cd
FROM gca_cbx_response_test a ,
gca_program_run_hist b ,
campaign_master c
WHERE a.list_id=b.list_id
AND a.run_seq=b.campaign_run_seq
AND b.campaign_cd=c.campaign_cd
AND a.resp_ts BETWEEN to_date('04-AUG-2005 00:01:32','DD-MON-YYYY HH24:MI:SS')
AND to_date('04-AUG-2005 00:01:32','DD-MON-YYYY HH24:MI:SS');
GROUP BY a.bcast_id ,
a.bcast_file_nm ,
a.clickthru_url_cd ,
a.list_id ,
a.prs_id ,
a.resp_cd ,
a.run_seq ,
c.src_grp_cd ,
b.site_cd; -
Problem with the query in group by clause
hi, i have problem with group by clause, can some one please help me.
select
header_id,
(select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
where
a1.country=a.country
and a1.source='AP'
and a1.header_id=a.header_id) WHT,
sum(dr),
sum(cr) from temp_tab a
group by header_id,
(select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
where
a1.country=a.country
and a1.source='AP'
and a1.header_id=a.header_id)
select * from temp_tab
drop table temp_tab
create table temp_tab(header_id number ,line_num number, country varchar2(2),
source varchar2(2), dr number, cr number,primary key(header_id,line_num));
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 1,'NL','AP',100,20);
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 2,'PO','AP',20,20);
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 3,'NL','AP',70,20);
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(2, 1,'NL','PA',100,20);
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(2, 2,'NL','PA',100,20);
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(3, 1,'KR','PO',100,20);
commit;
Appreciate your help.
Thanks,select header_id,
(select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
where a1.country=a.country
and a1.source='AP'
and a1.header_id=a.header_id) WHT,
sum(dr),
sum(cr)
from temp_tab a
group by header_id
,countryIt's kinda hard to follow what your query does... maybe because I'm only at my second coffee..
Edited by: Alex Nuijten on Oct 2, 2009 8:07 AM -
Improving Performance of Group By clause
I'm a developer who needs to create an aggreagate, or roll-up, of a large table (tens of millions of rows) using a group by clause. One of the several items I am grouping by is a numeric column called YEAR. My DBA recommended I create an index on YEAR to improve the performance of the group by clause. I read that indexes only are used when referenced in the where clause, which I do not need. Will my DBA's reccomendation help? Can you recommend a technique? Thank you.
When you select millions of rows, grouped or not, the database has to fetch
each of them, so an index on the group column isn't useful.
If you have a performance problem that cannot be solved through an index on
columns used in your where-clause, perhaps a materialzed view with the
dimension(s) of your group clause will help. -
Hi
I am using Oracle 8i and one of my queries is getting the data from multiple sources through a dblink from other databases (customer need cannot avoid dblinks).
The query is using the group by clause to get the count based on specific columns and when i am not using the group by the query is pretty fast.
select count(id), col1,col2,col3
from source1@dblink1,
source2@dblink1,
source3@dblink1,
source4@dblink1,
source5@dblink1
where
group by col1,col2,col3
Please suggest the use of other Oracle features that we can use (pl/sql table or looping in pl/sql instead of using group by ) as the amount of data is large and it has to go through several iterations and accordingly update my local db with the counts returned.
An example will be quite helpful.
Thanks in Advance.Hi,
i have a procedure that has a cursor thats using db links as above, in the code if i open the cursor and say NULL even then it is taking about 8 mins while the cursor query is taking about 2 mins only when run separately.
i open the cursor
for c1 in cursor loop
NULL;
end loop;
it hangs on for about 8 mins , while if i run the query of the cursor with the same parameters that i pass in the cursor at run time it takes about 2 mins.
Dont understand where the 6 mins are going.
If the cursor is not opened at all in the proc it gets executed in less than a second so there is no other code thats consuming time.
Please suggest. -
In evaluating several query plans, I've discovered several sqlstop messages that read:
<groupBy preclustered="true" sqlstop="Cannot generate SQL for the 'group-by' clause because it is not equivalent to the relational GROUP BY clause" stable="true">
I've examined the XQuery code and find no group clause and I can't find a reference to this message in the documentation or by googling the text. I assume that the grouping is being done implicitly by ODSI since it is not in the XQuery source. I have tried restructuring the code to no avail.
My question is -- is this causing me a performance problem since the sql is not generated, and if so, what steps must I take in the xquery structure to avoid this issue.
Many thanks to anyone who can provide some insight into this.
Regards,
PBis this causing me a performance problem since the sql is not generatedMy question is - why are you asking this question? :) Do you have a performance problem? The "Best Practices" posted as an announcement in this forum might help. Otherwise engage customer support.
To answer your question - your xquery likely generates nested/hierarchical xml - and looks something like below - which can be implemented with a sql left-outer-join ordered by CUSTOMER_ID of the customer-table, and taking the rows returned and ... grouping by CUSTOMER_ID to eliminate the duplicate customer information. So there's your group-by. But you cannot write sql that has a left-outer join, and then a group-by on the left-hand side. So the group by is done in the engine. Since the results are already sorted, the group-by in the engine simply skips over the duplicates (i.e. it's basically free).
for $c in CUSTOMER()
where $c/LAST_NAME = $lastname
return
<CUSTOMER>
... $c/CUSTOMER_ID ... (: in a left-outer-join, the CUSTOMER_ID is duplicated for every ORDER :)
{ for $o in ORDER()
where $o/CUSTOMER_ID eq $c/CUSTOMER_ID
return
</CUSTOMER> -
Aggregate functions without group by clause
hi friends,
i was asked an interesting question by my friend. The question is...
There is a DEPT table which has dept_no and dept_name. There is an EMP table which has emp_no, emp_name and dept_no.
My requirement is to get the the dept_no, dept_name and the no. of employees in that department. This should be done without using a group by clause.
Can anyone of you help me to get a solution for this?select distinct emp.deptno,dname
,count(*) over(partition by emp.deptno)
from emp
,dept
where emp.deptno=dept.deptno;
10 ACCOUNTING 3
20 RESEARCH 5
30 SALES 6 -
How to ORDER BY Different column than in the group by clause.
Hello, I have this sql statement
SELECT COUNT([Tags]) AS CNT, [Tags]
FROM [Tags], [Images]
WHERE
([Images].[Tags] LIKE '%' + [Tags].[LongTag] + '%') AND
([Tags].AllowTagPost = 'True' )
GROUP BY [Images].[Tags]
HAVING COUNT([Tags]) > 30
ORDER BY [Tags].[LastTagPost] DESC
It returns the tags, the number of occurances sorted by count. However, I want to sort it by a column in the Tags table named LastTagPost (DATETIME) The idea is to get the tag that hasn't been used in the longest time and also has more occurances
than 30 in the image table. When I try to order by this column i get an error that i'm sure most of you are all to familer with.
Error:
Column "Tags.LastTagPost" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
Any help would be greatly appreciated.Couldn't you just include the LastTagPost as a MIN?
DECLARE @tags TABLE (LastTagPost DATETIME, LongTag VARCHAR(100), allowTagPost CHAR(5))
DECLARE @images TABLE (tags VARCHAR(10))
SELECT COUNT(i.Tags) AS CNT, i.Tags, MIN(t.LastTagPost) AS lastTagPost
FROM @Tags t
INNER JOIN @Images i
ON i.Tags LIKE '%' + t.LongTag + '%'
WHERE t.AllowTagPost = 'True'
GROUP BY i.Tags
HAVING COUNT(i.Tags) > 30
ORDER BY LastTagPost DESC
Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question. -
Passing where and group by clause to cursor
I am working on a procedure that builds a where clause and needs a group by clause to return the correct results. I am trying to pass both the where and group by variables into the cursor.
The variables are getting populated correctly, but when the cursor gets created, the variables are not in the cursor.
Here is the code I'm working with. It is a part of a package, but makes no calls to other parts of the package.
PROCEDURE createFollowUpTask_Exposure( psUppgkedjetyp IN tis.tial.uppgkedjetyp%TYPE default NULL,
psAlarmtyp IN tis.tial.alarmtyp%TYPE default NULL,
psSubtyp IN tis.tial.subtyp%TYPE default NULL,
pnDays IN NUMBER default NULL,
psKampkod IN tis.tiin.kampkod%TYPE default NULL,
psKatnr IN tis.tiin.katnr%TYPE default NULL,
psUtgava IN tis.tiin.utgava%TYPE default NULL,
psKatslag IN tis.tikg.katslag%TYPE default NULL,
psProdsyst IN tis.tikg.prodsyst%TYPE default NULL,
psUppgtyp IN tis.tiin.uppgtyp%TYPE default NULL,
psProdkod IN tis.tiin.prodkod%TYPE default NULL,
psStatus IN tis.tiin.status%TYPE default NULL
) AS
cTIAL tis.tial%ROWTYPE;
vLopnr tis.tial.lopnr%TYPE;
vSqlWhere VARCHAR2(4000);
vGroupBy VARCHAR2(1000) := ' tiin.kampkod, tiin.abnr, tiko.fordsalj';
cSelectCursor SYS_REFCURSOR;
vSqlSelect VARCHAR2(4000);
psDays VARCHAR2(50);
cRec T_TIAL_REC;
nCount number := 0;
CURSOR cSqlSelect( SqlWhere IN VARCHAR2, GroupBy IN VARCHAR2) IS
SELECT tiin.kampkod, tiin.abnr, tiko.fordsalj, MAX(tici.regdat) ALARMDATE
FROM tis.tiin
JOIN tis.tiko ON tiin.kampkod = tiko.kampkod AND tiin.abnr = tiko.abnr
JOIN core.tici ON tiin.kampkod = tici.kampkod AND tiin.abnr = tici.abnr AND tici.inplnr = tiin.inplnr
WHERE 1=1 || SqlWhere
GROUP BY GroupBy;
BEGIN
-- If these parameters are null, raise error
IF psUppgkedjetyp IS NULL and psSubtyp IS NULL THEN
raise_application_error(-20001,
'Either Event Chain or Starting Event must be assigned');
END IF;
-- Populate TIAL values
IF psUppgkedjetyp IS NOT NULL THEN
cTIAL.Uppgkedjetyp := psUppgkedjetyp;
END IF;
IF psAlarmtyp IS NOT NULL THEN
cTIAL.Alarmtyp := psAlarmtyp;
END IF;
cTIAL.Handklass := 'T';
cTIAL.Blobid := 0;
IF pnDays IS NOT NULL THEN
psDays := '+ '||pnDays;
END IF;
IF psSubtyp IS NOT NULL THEN
cTIAL.Subtyp := psSubtyp;
END IF;
-- Create Where clause for cursor
vSqlWhere := '';
IF psKampkod IS NOT NULL THEN
vSqlWhere := vSqlWhere||' AND tiin.kampkod = '''|| psKampkod||'''';
END IF;
IF psKatnr IS NOT NULL THEN
vSqlWhere := vSqlWhere||' AND tiin.katnr = '''||psKatnr||'''';
END IF;
IF psUtgava IS NOT NULL THEN
vSqlWhere := vSqlWhere||' AND tiin.utgava = '''||psUtgava||'''' ;
END IF;
IF psKatslag IS NOT NULL THEN
vSqlWhere := vSqlWhere||' AND tikg.katslag = '''||psKatslag||'''';
END IF;
IF psProdsyst IS NOT NULL THEN
vSqlWhere := vSqlWhere||' AND tikg.prodsyst = '''||psProdsyst||'''';
END IF;
IF psUppgtyp IS NOT NULL THEN
vSqlWhere := vSqlWhere||' AND tiin.uppgtyp = '''||psUppgtyp||'''';
END IF;
IF psProdkod IS NOT NULL THEN
vSqlWhere := vSqlWhere||' AND tiin.prodkod = '''||psProdkod||'''';
END IF;
IF psStatus IS NOT NULL THEN
vSqlWhere := vSqlWhere||' AND tiin.status = '''||psStatus||'''';
END IF;
-- Loop through all records meeting input parameters and set required TIAL values.
FOR i IN cSqlSelect(vSqlWhere, vGroupBy)
LOOP
--FETCH cSelectCursor INTO cRec;
cTIAL.Kampkod := '';
cTIAL.Abnr := '';
cTIAL.Sign := '';
cTIAL.Alarmdate := '';
cTIAL.Kampkod := i.Kampkod;
cTIAL.Abnr := i.Abnr;
cTIAL.Sign := i.fordsalj;
cTIAL.Alarmdate := i.alarmdate;
nCount := nCount + 1;
IF vLopnr = -1 THEN
raise_application_error(-20002,
'Error Creating task for: '||cTIAL.Kampkod||' '||cTIAL.Abnr||' Sales Rep: '||cTIAL.Alarmdate);
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE('I created '||nCount||' records.');
END createFollowUpTask_Exposure;
Thanks in advance for any help.Hi,
Welcome to the forum!
Try this (not tested) as an example:
PROCEDURE createFollowUpTask_Exposure(psUppgkedjetyp IN tis.tial.uppgkedjetyp%TYPE DEFAULT NULL,
psAlarmtyp IN tis.tial.alarmtyp%TYPE DEFAULT NULL,
psSubtyp IN tis.tial.subtyp%TYPE DEFAULT NULL,
pnDays IN NUMBER DEFAULT NULL,
psKampkod IN tis.tiin.kampkod%TYPE DEFAULT NULL,
psKatnr IN tis.tiin.katnr%TYPE DEFAULT NULL,
psUtgava IN tis.tiin.utgava%TYPE DEFAULT NULL,
psKatslag IN tis.tikg.katslag%TYPE DEFAULT NULL,
psProdsyst IN tis.tikg.prodsyst%TYPE DEFAULT NULL,
psUppgtyp IN tis.tiin.uppgtyp%TYPE DEFAULT NULL,
psProdkod IN tis.tiin.prodkod%TYPE DEFAULT NULL,
psStatus IN tis.tiin.status%TYPE DEFAULT NULL) AS
cTIAL tis.tial%ROWTYPE;
vLopnr tis.tial.lopnr%TYPE;
vSqlWhere VARCHAR2(4000);
vGroupBy VARCHAR2(1000) := ' tiin.kampkod, tiin.abnr, tiko.fordsalj';
cSelectCursor SYS_REFCURSOR;
vSqlSelect VARCHAR2(4000);
psDays VARCHAR2(50);
cRec T_TIAL_REC;
nCount NUMBER := 0;
FUNCTION fnc_cSqlSelect(SqlWhere IN VARCHAR2,
GroupBy IN VARCHAR2) RETURN VARCHAR2 IS
BEGIN
RETURN 'SELECT tiin.kampkod,
tiin.abnr,
tiko.fordsalj,
MAX(tici.regdat) ALARMDATE
FROM tis.tiin
JOIN tis.tiko ON tiin.kampkod = tiko.kampkod
AND tiin.abnr = tiko.abnr
JOIN core.tici ON tiin.kampkod = tici.kampkod
AND tiin.abnr = tici.abnr
AND tici.inplnr = tiin.inplnr
WHERE 1 = 1 ' || SqlWhere || ' GROUP BY ' || GroupBy;
END fnc_cSqlSelect;
BEGIN
-- If these parameters are null, raise error
IF psUppgkedjetyp IS NULL AND psSubtyp IS NULL THEN
raise_application_error(-20001,
'Either Event Chain or Starting Event must be assigned');
END IF;
-- Populate TIAL values
IF psUppgkedjetyp IS NOT NULL THEN
cTIAL.Uppgkedjetyp := psUppgkedjetyp;
END IF;
IF psAlarmtyp IS NOT NULL THEN
cTIAL.Alarmtyp := psAlarmtyp;
END IF;
cTIAL.Handklass := 'T';
cTIAL.Blobid := 0;
IF pnDays IS NOT NULL THEN
psDays := '+ ' || pnDays;
END IF;
IF psSubtyp IS NOT NULL THEN
cTIAL.Subtyp := psSubtyp;
END IF;
-- Create Where clause for cursor
vSqlWhere := '';
IF psKampkod IS NOT NULL THEN
vSqlWhere := vSqlWhere || ' AND tiin.kampkod = ''' || psKampkod || '''';
END IF;
IF psKatnr IS NOT NULL THEN
vSqlWhere := vSqlWhere || ' AND tiin.katnr = ''' || psKatnr || '''';
END IF;
IF psUtgava IS NOT NULL THEN
vSqlWhere := vSqlWhere || ' AND tiin.utgava = ''' || psUtgava || '''';
END IF;
IF psKatslag IS NOT NULL THEN
vSqlWhere := vSqlWhere || ' AND tikg.katslag = ''' || psKatslag || '''';
END IF;
IF psProdsyst IS NOT NULL THEN
vSqlWhere := vSqlWhere || ' AND tikg.prodsyst = ''' || psProdsyst || '''';
END IF;
IF psUppgtyp IS NOT NULL THEN
vSqlWhere := vSqlWhere || ' AND tiin.uppgtyp = ''' || psUppgtyp || '''';
END IF;
IF psProdkod IS NOT NULL THEN
vSqlWhere := vSqlWhere || ' AND tiin.prodkod = ''' || psProdkod || '''';
END IF;
IF psStatus IS NOT NULL THEN
vSqlWhere := vSqlWhere || ' AND tiin.status = ''' || psStatus || '''';
END IF;ç
-- Loop through all records meeting input parameters and set required TIAL values.
OPEN cSelectCursor FOR fnc_cSqlSelect(vSqlWhere,
vGroupBy);
LOOP
FETCH cSelectCursor
INTO v; -- You must define a variable 'v' to hold the data of cursor
EXIT WHEN cSelectCursor%NOTFOUND;
--FETCH cSelectCursor INTO cRec;
cTIAL.Kampkod := '';
cTIAL.Abnr := '';
cTIAL.Sign := '';
cTIAL.Alarmdate := '';
cTIAL.Kampkod := i.Kampkod;
cTIAL.Abnr := i.Abnr;
cTIAL.Sign := i.fordsalj;
cTIAL.Alarmdate := i.alarmdate;
nCount := nCount + 1;
IF vLopnr = -1 THEN
raise_application_error(-20002,
'Error Creating task for: ' || cTIAL.Kampkod || ' ' ||
cTIAL.Abnr || ' Sales Rep: ' || cTIAL.Alarmdate);
END IF;
END LOOP;
CLOSE cSelectCursor;
DBMS_OUTPUT.PUT_LINE('I created ' || nCount || ' records.');
END createFollowUpTask_Exposure;
/Regards, -
Can't understand how this group by clause works
The Schema is as below: (http://www.psoug.org/reference/rollup.html)
CREATE TABLE grp_rep (
person_id NUMBER(3),
division VARCHAR2(3),
commission NUMBER(5));
INSERT INTO grp_rep VALUES (1,'SAM',1000);
INSERT INTO grp_rep VALUES (2,'EUR',1200);
INSERT INTO grp_rep VALUES (1,'EUR',1450);
INSERT INTO grp_rep VALUES (1,'EUR',700);
INSERT INTO grp_rep VALUES (2,'SEA',1000);
INSERT INTO grp_rep VALUES (2,'SEA',2000);
INSERT INTO grp_rep VALUES (1,'EUR',800);
COMMIT;
Query1:
SELECT person_id, division, SUM(commission)
FROM grp_rep
GROUP BY person_id, ROLLUP (person_id, division);
Query2:
SELECT person_id, division, SUM(commission)
FROM grp_rep
GROUP BY division, ROLLUP (person_id, division);
The results of query1 are okay. It has results from rollup and group by person_id.
But, in Query2 results of rollup are missing and results of group by division is there.
Anyone can explain how the group by clause works when there are multiple columns involving CUBE, ROLLUP and simple column names?
Regards.Thank you shoblock!
but, What i m really looking for is,
How group by clause works when i add regular column along with RollUp in group by clause?
I have understood simple group by clause like
...group by column1,column2,column3....
n I also know simple rollup clauses like
...group by rollup(column1,column2,column3,...)
But my Problem is how does this work:
...group by column2,rollup(column1,column2,...)
...group by column1,rollup(column1,column2,...)
See below Results:
Query1:
SELECT person_id, division, SUM(commission)
FROM grp_rep
GROUP BY person_id,ROLLUP ( person_id, division );
Result:
PERSON_ID DIVISION SUM(COMMISSION)
1 EUR 2950
1 SAM 1000
2 EUR 1200
2 SEA 3000
1 3950
2 4200
1 3950
2 4200
SELECT person_id, division, SUM(commission)
FROM grp_rep
GROUP BY division,ROLLUP ( person_id, division );
Query2:
SELECT person_id, division, SUM(commission)
FROM grp_rep
GROUP BY division,ROLLUP ( person_id, division );
Result:
PERSON_ID DIVISION SUM(COMMISSION)
1 EUR 2950
2 EUR 1200
1 SAM 1000
2 SEA 3000
1 EUR 2950
2 EUR 1200
1 SAM 1000
2 SEA 3000
EUR 4150
SAM 1000
SEA 3000
guys, help me make understand above results!
Regards.
Maybe you are looking for
-
I reset my WRT54G and now I can't get online.
I did a factory reset of my WRT54G v.2 last night after I was unable to access the router's setting to set up a WEP password (couldn't remember login/pass and the default login wasn't working) and now I can not connect to the internet through my rout
-
How i use my isight to chat in adium with msn users
I like Know how i use my isight (built-it in a MB) to chat in adium with msn users
-
Scripting: One layer to adjust opacity of other layers?
Hi there, i've a lot of layers in my comp which names start with "POINTER_". I would need those layers to fade out at the same time. But i can't subcomp them or use stencil alpha. I'm sure it is possible to do a script on an adjustment layer that wou
-
Hi guys, I have 2 flat files and am trying to mingle them to the infocube. My question is how can i if its possible to create 2 datasources in a infosource or any other method as such to do so.. regards sri
-
Hi there We have legacy License number which is equal to Customer number in legacy system, we used ORIG_SYSTEM_REFERENCE field as a license number in Oracle Receivable Customer form. What happened this field is not updateable and the some time user f