GROUP BY clause with Alias
Hi,
I am trying to run following query and i tried to run littel different way but no luck.
If someone can help me out.
I know that icann't use the alias in GROUP BY clause.
I am getting errors like "NOT a GROUP BY Function" or Identifier is not valid within my different fromat of the sql.
For C_CODE (MAx function part_, i have to make a header for each C__CODE and put the corrospondence value for S_TASK.
SELECT s_name ,login, f_name, l_name, email, S_ID, S_EMAIL,
desc, wave,
MAX(DECODE(C_CODE, '100',S_TASK, '')) "100",
MAX(DECODE(C_CODE, '150',S_TASK, '')) "150",
MAX(DECODE(C_CODE, '200',S_TASK, '')) "200"
FROM
SELECT b.S_name, d.login, d.f_name,d.l_name, d.email,
*(SELECT d.login FROM user d WHERE d.id = c.rep_to_id) AS S_ID,*
*(SELECT d.email FROM user d WHERE d.id = c.rep_to_id) AS S_EMAIL,*
e.desc, f.wave, C_CODE, S_TASK
FROM CT_E_STAK_MAP A,
ct_stak B,
e_info C,
user D,
e_code E,
e_web_info F,
C_STAK_MAP G,
C_CORS H,
C_S_TASK I,
C_S_STAK_MAP J
WHERE a.C_stak_id = b.c_stak_id
AND b.c_stak_id = G.c_stak_id
AND B.C_STAK_ID = J.C_STAK_ID
AND J.C_S_TASK_ID = I.C_S_TASK_ID
AND G.C_CORS_ID = H.C_CORS_ID
AND a.U_id = c.U_id
AND a.U_id = d.id
AND d.id = f.U_id
AND c.ctll3 = e.c_st_val
AND c.ctl1_2 = e.ctl1_2
AND e.c_set_name = 'EY'
AND c.active = 1
GROUP BY b.s_name, d.login, d.f_name,d.l_name, d.email,d.login, d.email, S_ID, S_EMAIL,
e.desc, f.wave, C_CODE, S_TASK
GROUP BY s_name ,login, f_name, l_name, email, S_ID, S_EMAIL, desc, wave
Please let me know if you need more info.
Thanks for your help!
<ul><li>Thanks for your help!
I tried to import your query into my existing query but getting error.
I love to post table/Insert script but i have lots of join tables and also using to retrieve data from those tables in my output results.
If you see my original query then still you need crate table / Insert data script then please let me know.
This is my original query:
<ul><li>SELECT s_name ,login, f_name, l_name, email, S_ID, S_EMAIL,</li>
<li>desc, wave, </li>
<li>MAX(DECODE(C_CODE, '100',S_TASK, '')) "100",</li>
<li>MAX(DECODE(C_CODE, '150',S_TASK, '')) "150",</li>
<li>MAX(DECODE(C_CODE, '200',S_TASK, '')) "200"</li>
<li>FROM </li>
<li>+(+</li>
<li>SELECT b.S_name, d.login, d.f_name,d.l_name, d.email,</li>
<li>+(SELECT d.login FROM user d WHERE d.id = c.rep_to_id) AS S_ID,+</li>
<li>+(SELECT d.email FROM user d WHERE d.id = c.rep_to_id) AS S_EMAIL,+</li>
<li>e.desc, f.wave, C_CODE, S_TASK</li>
<li> FROM CT_E_STAK_MAP A,</li>
<li> ct_stak B,</li>
<li> e_info C,</li>
<li> user D,</li>
<li> e_code E,</li>
<li> e_web_info F, </li>
<li> C_STAK_MAP G,</li>
<li> C_CORS H, </li>
<li> C_S_TASK I,</li>
<li> C_S_STAK_MAP J</li>
<li>WHERE a.C_stak_id = b.c_stak_id </li>
<li>AND b.c_stak_id = G.c_stak_id</li>
<li>AND B.C_STAK_ID = J.C_STAK_ID</li>
<li>AND J.C_S_TASK_ID = I.C_S_TASK_ID</li>
<li>AND G.C_CORS_ID = H.C_CORS_ID</li>
<li>AND a.U_id = c.U_id </li>
<li>AND a.U_id = d.id </li>
<li>AND d.id = f.U_id </li>
<li>AND c.ctll3 = e.c_st_val </li>
<li>AND c.ctl1_2 = e.ctl1_2 </li>
<li>AND e.c_set_name = 'EY' </li>
<li>AND c.active = 1</li>
<li>GROUP BY b.s_name, d.login, d.f_name,d.l_name, d.email,d.login, d.email, S_ID, S_EMAIL,</li>
<li> e.desc, f.wave, C_CODE, S_TASK</li>
<li>+)+</li>
<li>GROUP BY s_name ,login, f_name, l_name, email, S_ID, S_EMAIL, desc, wave</li>
</ul>
</li>
<li>I tried include your query in my block</li>
<li><ul><li>SELECT s_name ,login, f_name, l_name, email, S_ID, S_EMAIL,</li>
<li>desc, wave, </li>
<li>+(SELECT DISTINCT+</li>
<li> +', COUNT (CASE WHEN C_CODE = '''+</li>
<li>+|| C_CODE+</li>
<li>+|| ''' ' AS txt1+</li>
<li>+, 'THEN 1 END) AS '+</li>
<li>+|| C_CODE+</li>
<li>+|| '_CNT' AS txt2+</li>
<li>FROM C_CORS H1</li>
<li>ORDER BY txt1)</li>
<li>FROM </li>
<li>+(+</li>
<li>SELECT b.S_name, d.login, d.f_name,d.l_name, d.email,</li>
<li>+(SELECT d.login FROM user d WHERE d.id = c.rep_to_id) AS S_ID,+</li>
<li>+(SELECT d.email FROM user d WHERE d.id = c.rep_to_id) AS S_EMAIL,+</li>
<li>e.desc, f.wave, C_CODE, S_TASK</li>
<li> FROM CT_E_STAK_MAP A,</li>
<li> ct_stak B,</li>
<li> e_info C,</li>
<li> user D,</li>
<li> e_code E,</li>
<li> e_web_info F, </li>
<li> C_STAK_MAP G,</li>
<li> C_CORS H, </li>
<li> C_S_TASK I,</li>
<li> C_S_STAK_MAP J</li>
<li>WHERE a.C_stak_id = b.c_stak_id </li>
<li>AND b.c_stak_id = G.c_stak_id</li>
<li>AND B.C_STAK_ID = J.C_STAK_ID</li>
<li>AND J.C_S_TASK_ID = I.C_S_TASK_ID</li>
<li>AND G.C_CORS_ID = H.C_CORS_ID</li>
<li>AND a.U_id = c.U_id </li>
<li>AND a.U_id = d.id </li>
<li>AND d.id = f.U_id </li>
<li>AND c.ctll3 = e.c_st_val </li>
<li>AND c.ctl1_2 = e.ctl1_2 </li>
<li>AND e.c_set_name = 'EY' </li>
<li>AND c.active = 1</li>
<li>GROUP BY b.s_name, d.login, d.f_name,d.l_name, d.email,d.login, d.email, S_ID, S_EMAIL,</li>
<li> e.desc, f.wave, C_CODE, S_TASK</li>
<li>+)+</li>
<li>GROUP BY s_name ,login, f_name, l_name, email, S_ID, S_EMAIL, desc, wave</li>
</ul>
</li>
<li>I want result like:</li>
<li>+
S_name ,login, f_name, l_name, email, S_ID, S_EMAIL, desc, wave, C_Code1, C_code2, C_Code (This will dynamically)
+p p1 p1s s [[email protected]|mailto:[email protected]] d1 [[email protected]|mailto:[email protected]] 'test' wave1 Eco Math Eng....+
+</li>
</ul>
+
I hope explained properly what you are asking.+
+Thanks once again!
+
Similar Messages
-
ORA-00907: missing right parenthesis when using group by clause with xmlagg
I have the following query and I am getting ORA 00907 Error when I am using group by clause with the xmlagg function.
select xmlelement("Mitigation",
xmlelement("m_szMethodName",tm.DisplayName),
xmlelement("SubstanceInterferenceProtocolList",
(select xmlagg(xmlelement("MitigationProtocol",
xmlelement("m_szMethodName",tm.DisplayName),
xmlelement("m_szInterferenceProtocolName",tmp.protocol_name),
xmlelement("m_szInterferenceSubstance",tmp.intf_mtrl_prod_code),
xmlelement("m_ProtocolParameters",
xmlelement("m_szProtocolName",tmp.protocol_name),
xmlelement("m_Consumables",
xmlelement("Consumable",
xmlelement("m_szConsumId", xrl.rgnt_pack_name),
xmlelement("m_szProductCode",xrl.pack_prod_code),
xmlelement("m_nVolume",tmp.fluid_vol),
xmlelement("m_szProtocolStep",xps.protocol_step_name))),
xmlelement("m_ProtParamList",
xmlagg(
xmlelement("ParameterValues",
xmlelement("m_szProtocolName",tmp.protocol_name),
xmlelement("m_Time",xpsd.parameter_ntime_value))
group by tmp.ccd_test_id,tmp.intf_mtrl_prod_code)
order by tmp.ccd_test_id, tmp.intf_mtrl_prod_code, xps.protocol_step_intprotocolstep )
from XPR_tdef_mitigation_protocol tmp, xp_reagentlist xrl,
xpr_protocol_settings xps, xpr_protocol_settings_default xpsd
where tmp.ccd_test_id = tm.ccd_test_id
and tmp.ccd_test_id = xrl.ccd_test_id
and tmp.pack_prod_code = xrl.pack_prod_code
and tmp.intf_type = 1
and xps.protocol_name = xpsd.protocol_name
and xps.protocol_step_name = xpsd.protocol_step_name
and xps.ps_action_parameterlist = xpsd.ps_action_parameterlist
and xps.protocol_name = tmp.PROTOCOL_NAME
from XPtoXPRTdef_defn_mapping tm
where tm.DisplayName = 'SYPH'If I remove the xmlagg clause along with the group by clause, the query runs fine and give me the output.
But in that XML format of the output is incorrect for my application.
Could someone help here?Hi,
userAtoZ wrote:
I have the following query and I am getting ORA 00907 Error when I am using group by clause with the xmlagg function.
... xmlagg(
xmlelement("ParameterValues",
xmlelement("m_szProtocolName",tmp.protocol_name),
xmlelement("m_Time",xpsd.parameter_ntime_value))
group by tmp.ccd_test_id,tmp.intf_mtrl_prod_code)Please don't post unformatted code. When posting any formatted text on this site, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
If the code above were formatted well, so that you could match each '(' with its closing ')', it would look something like this:... xmlagg ( xmlelement ( "ParameterValues"
, xmlelement ( "m_szProtocolName"
, tmp.protocol_name
, xmlelement ( "m_Time"
, xpsd.parameter_ntime_value
group by tmp.ccd_test_id
, tmp.intf_mtrl_prod_code
This is exactly what you posted, only the whitespace has been changed.
This makes it clear that the GROUP BY is inside the parentheses with the argument to XMLAGG. You can have an ORDER BY clause there, but not a GROUP BY clause. -
Help combining a GROUP BY clause with a ROWNUM
Hi Folks,
I have a simple query request that I need to perform in my data warehouse
(well I am sure it is simple for you guys, but I am no to this )
The requirement is: Show the TOP 2 theatres by the value of ticket sales.
This information is contained in my fact table: FactTicketPurchase. Here is a sample of the data:
Select * from TicketPurchase:
TICKETPURCHASEID
CLIENTID
PRODUCTIONID
THEATREID
TIMEID
TROWID
SUMTOTALAMOUNT
60006
2527
66
21
942
40
7
60007
2527
72
21
988
36
6
60008
2527
74
21
1001
40
6
60009
2527
76
21
1015
37
6
60010
2527
79
21
1037
39
6
60011
2527
79
21
1038
37
7
So here is the initial query I envisaged (which I believe is correct?)
SELECT TheatreID, SUM(SumtotalAmount) SumTotalAmount
FROM FactTicketPurchase
GROUP BY TheatreID
ORDER BY SumTotalAmount DESC;
The above query returned to me 6 rows (that is, one for each Theatre registered in the fact table):
THEATREID
SUMTOTALAMOUNT
21
20908
25
19365
22
15232
23
14022
24
13667
26
13028
However, since the requirement is to return only the TOP 2 theatres, I would like my query above to only return the top two rows, which are the theatres whose IDs are 21 and 25.
I tried using ROWNUM but that doesn't give the result I expected (and I know why! makes sense ) But I don't know then how to obtain the result I'd like.
Could someone please advise?
Regards,
P.Hi Frank,
Thanks a lot for your explanation. I've been using indentation to format my queries, but not always. I will stick to it from now on.
I think I have a vague idea of the issues between ROWNUM and the analytical function you mentioned. I am wrecking my head with another requirement, which so fat I didn't manage to easily solve it with ROWNUM. I was thinking of posting another question, but let me run it through with you first and if you believe I should post another question, I will be glad to abide.
I need to obtain the most popular row type in each theatre by value of ticket sale per row. To complicate things, each theatre has different row configurations (eg: theatre A can have 3 front rows, 2 middle rows and 2 rear rows, while theatre B can have 2 front rows, 3 middle rows and 1 back row).
To achieve the requirement, I started with the following code initial code:
SELECT * FROM
(SELECT DimTHE.Name, DimTRO.RowType, AVG(SumTotalAmount) SumTotalAmount
FROM FactTicketPurchase FacTIC, DimTheatre DimTHE, DimTRow DimTRO
WHERE FacTIC.TheatreID = DimTHe.TheatreID
AND FacTIC.TRowID = DimTRO.TRowID
GROUP BY DimTHE.Name, DimTRO.RowType
ORDER BY DimTHE.Name, SumTotalAmount DESC)
Here is an example of what this code returns:
NAME
ROWTYPE
SUMTOTALAMOUNT
BEESTON
Front
6.49599083619702176403207331042382588774
BEESTON
Rear
6.47465437788018433179723502304147465438
BEESTON
Middle
6.45626477541371158392434988179669030733
BIRSTALL
Rear
6.51990349819059107358262967430639324487
BIRSTALL
Middle
6.48612153038259564891222805701425356339
BIRSTALL
Front
6.4804878048780487804878048780487804878
CLINTON
Middle
6.5
CLINTON
Rear
6.47835990888382687927107061503416856492
CLINTON
Front
6.46948941469489414694894146948941469489
The issue here is that I would only like the 'TOP' (i.e.: MAX) row to be returned for each theatre. And I have to idea on how to do that by simply using ROWNUM and sub-queries. Is that possible at all?
Again, I'd be happy to post this as a new question if required. But I am under the impression this is still part of the same subject... -
Hi,
I have four columns in group by clause. I want to add conditional group by clause.
Case 1 : If one of the column's value is null, I don't want to include it in group by clause. Means, Now GROUP BY clause will have only 3 columns.
Case 2 : If not null, then GROUP BY clause with all four columns.
Please help me out on this.
Thanks in advance.Hi
I think it won't matter, all group functions by default ignore NULLs so your result won't differ.
select dept, loc, sum(sal)
from (
select 'A' emp , 1 dept , 'P' loc , 100 sal from dual union all
select'B',1,'P',200 from dual union all
select'C',2,'P',300 from dual union all
select'D',2,'P',400 from dual union all
select'E',3, 'P',500 from dual union all
select'F',3, 'P',600 from dual union all
select'G',4, 'Q',700 from dual union all
select'H', null,'Q' , 1000 from dual union all
select'I',null ,'Q', 2000 from dual union all
select 'J' ,null, 'Q',300 from dual)
group by dept,loc;
Output
DEPT LOC SUM(SAL)
1 P 300
2 P 700
3 P 1100
Q 3300
4 Q 700
Now by doing grouping only for NOT NULL values,
select dept,loc, sum(sal)
from (
select 'A' emp , 1 dept , 'P' loc , 100 sal from dual union all
select'B',1,'P',200 from dual union all
select'C',2,'P',300 from dual union all
select'D',2,'P',400 from dual union all
select'E',3, 'P',500 from dual union all
select'F',3, 'P',600 from dual union all
select'G',4, 'Q',700 from dual union all
select'H', null,'Q' , 1000 from dual union all
select'I',null ,'Q', 2000 from dual union all
select 'J' ,null, 'Q',300 from dual)
where dept is not null --------------NOT NULL Condition
group by dept, loc;
Output
DEPT LOC SUM(SAL)
1 P 300
2 P 700
3 P 1100
4 Q 700
Now by doing grouping only for NULL values,
select dept,loc, sum(sal)
from (
select 'A' emp , 1 dept , 'P' loc , 100 sal from dual union all
select'B',1,'P',200 from dual union all
select'C',2,'P',300 from dual union all
select'D',2,'P',400 from dual union all
select'E',3, 'P',500 from dual union all
select'F',3, 'P',600 from dual union all
select'G',4, 'Q',700 from dual union all
select'H', null,'Q' , 1000 from dual union all
select'I',null ,'Q', 2000 from dual union all
select 'J' ,null, 'Q',300 from dual)
where dept is null --------------NULL Condition
group by dept, loc;
Output
DEPT LOC SUM(SAL)
Q 3300
The output is same for both the conditions. -
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$_"}}) -
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 -
Analytic Functions with GROUP-BY Clause?
I'm just getting acquainted with analytical functions. I like them. I'm having a problem, though. I want to sum up the results, but either I'm running into a limitation or I'm writing the SQL wrong. Any hints for me?
Hypothetical Table SALES consisting of a DAY_ID, PRODUCT_ID, PURCHASER_ID, PURCHASE_PRICE lists all the
Hypothetical Business Question: Product prices can fluctuate over the course of a day. I want to know how much per day I would have made had I sold one each of all my products at their max price for that day. Silly question, I know, but it's the best I could come up with to show the problem.
INSERT INTO SALES VALUES(1,1,1,1.0);
INSERT INTO SALES VALUES(1,1,1,2.0);
INSERT INTO SALES VALUES(1,2,1,3.0);
INSERT INTO SALES VALUES(1,2,1,4.0);
INSERT INTO SALES VALUES(2,1,1,5.0);
INSERT INTO SALES VALUES(2,1,1,6.0);
INSERT INTO SALES VALUES(2,2,1,7.0);
INSERT INTO SALES VALUES(2,2,1,8.0);
COMMIT;
Day 1: Iif I had sold one product 1 at $2 and one product 2 at $4, I would have made 6$.
Day 2: Iif I had sold one product 1 at $6 and one product 2 at $8, I would have made 14$.
The desired result set is:
DAY_ID MY_MEASURE
1 6
1 14The following SQL gets me tantalizingly close:
SELECT DAY_ID,
MAX(PURCHASE_PRICE)
KEEP(DENSE_RANK FIRST ORDER BY PURCHASE_PRICE DESC)
OVER(PARTITION BY DAY_ID, PRODUCT_ID) AS MY_MEASURE
FROM SALES
ORDER BY DAY_ID
DAY_ID MY_MEASURE
1 2
1 2
1 4
1 4
2 6
2 6
2 8
2 8But as you can see, my result set is "longer" than I wanted it to be. I want a single row per DAY_ID. I understand what the analytical functions are doing here, and I acknowledge that I am "not doing it right." I just can't seem to figure out how to make it work.
Trying to do a sum() of max() simply does not work, nor does any semblance of a group-by clause that I can come up with. Unfortunately, as soon as I add the windowing function, I am no longer allowed to use group-by expressions (I think).
I am using a reporting tool, so unfortunately using things like inline views are not an option. I need to be able to define "MY_MEASURE" as something the query tool can apply the SUM() function to in its generated SQL.
(Note: The actual problem is slightly less easy to conceptualize, but solving this conundrum will take me much closer to solving the other.)
I humbly solicit your collective wisdom, oh forum.Thanks, SY. I went that way originally too. Unfortunately that's no different from what I could get without the RANK function.
SELECT DAY_ID,
PRODUCT_ID,
MAX(PURCHASE_PRICE) MAX_PRICE
FROM SALES
GROUP BY DAY_ID,
PRODUCT_ID
ORDER BY DAY_ID,
PRODUCT_ID
DAY_ID PRODUCT_ID MAX_PRICE
1 1 2
1 2 4
2 1 6
2 2 8 -
Aggregate fuction with group by clause
Hello,
Following is assignment is given but i dont get correct output
so please i am request to all of us write code to solve my problem.
There can be multiple records for one customer in VBAK tables with different combinations.
Considering that we do not need details of each sales order,
use Aggregate functions with GROUP BY clause in SELECT to read the fields.
<garbled code removed>
Moderator Message: Please paste the relevant portions of the code
Edited by: Suhas Saha on Nov 18, 2011 1:48 PMSo if you need not want all the repeated records, then you select all the values to an Internal table,
and declare an internal table of same type and Usee COLLECT
for ex:
itab1 type <xxxx>.
wa_itba like line of itab1.
itab2 type <xxxx>. "<-This should be same type of above.
select * from ..... into table itab1.
and now...
loop at itab1 into wa_itab.
collect wa_itab1 into itab2.
endloop.
then you will get your desired result.. -
Default Sorting behaviour of Oracle 9i in 11g along with group by clause
Hi,
We have recently migrated from 9i to 11g. The reports from application comes in a jumbled fashion. Later we understood when there is a group by clause in the query, the recordset will be sorted by default in 9i and this feature is not available in 11g. Do anyone faced the same issue and resolved at the DB level.
Only alternate we found is the change in code with addittional order by clause which will take a long time to complete and roll out the same.
If anyone has got any immediate solution, please let me know.
Thx in advance.
SheenHi,
A group by can sort (depending on the method of grouping) but it isn't necessary. If you want to sort the output you need the ORDER BY clause. There are different group by mechanismes between 9i and 11g. 10g introduced HASH GROUP BY where in 9i only the SORT GROUP BY existed. The latter gives a sorted set, the first not.
if you want the same behaviour you can use "_gby_hash_aggregation_enabled parameter" = false, which disables the hash group by.
Have also a look at the support document "'Group By' Does Not Guarantee a Sort Without Order By Clause In 10g and Above [ID 345048.1]".
Herald ten Dam
http://htendam.wordpress.com -
Strange behavior in inner query with group by clause
Hi All,
I found a very strange behaviour with Inner query having a group by clause.
Please look the sample code
Select b,c,qty from (select a,b,c,sum(d) qty from tab_xyz group by b,c);
This query gives output by summing b,c wise. But when i run the inner query it gives error as "not a group by expression "
My question is - though the inner query is wrong, how is it possible that this query gives output.
it behaves like -
Select b,c,qty from (select b,c,sum(d) qty from tab_xyz group by b,c);
Is it a normal behaviour ?
If it is a normal behaviour, then how group by behaves inside a inner query.
Thanks !!This case I have tested already and it throws error.
But why the initial posted query is not throwing
error even the inner query is wrong.
In what way oracle behaves for the initial posted
query?what is the scenario that throws the error? is it at the time when you only run the inner query or the whole query? -
Reg - Search Form for a VO with group by clause
Hi,
I have a Bar graph that displays data based on the Query below.
SELECT STATUS.STATUS_ID AS STATUSID,STATUS.STATUS,COUNT(SR.SERVICEREQUEST_ID) AS SRCOUNT
FROM SERVICE_REQUEST SR ,SERVICEREQUESTSTATUS STATUS
WHERE SR.STATUS_ID = STATUS.STATUS_ID
GROUP BY STATUS.STATUS_ID,STATUS.STATUS,SR.STATUS_ID
It displays the count of SRs against a particular status.
Now I need to add a search form to this graph with customer and date range.
So we need to add the line below to the where clause.
"SR.CUSTOMER_ID = :customerId AND SR.REQUESTED_ON BETWEEN :fromDate and :toDate"
But the columns SR.CUSTOMER_ID, SR.REQUESTED_ON also need to be added to the select clause to create the View criteria for search panel.
The two columns should also need to be added to the group by clause if we are to add them in the select clause.
This would not produce the expected results.
How do I create a search form with the criterias applied only at the where clause.Please help.
With Regards,
GunaThe [url http://docs.oracle.com/cd/E16162_01/apirefs.1112/e17483/oracle/jbo/server/ViewObjectImpl.html]ViewObjectImpl has methods for doing this programmatically (setQuery, defineNamedWhereClauseParam, setNamedWhereClauseParam) that you can use to manipulate the query, the bind variables expected, and the values for the binds.
John -
Incorrect warning when parsing query with group by clause
I am using SQL Developer 4.0.0.13.80 with JDK 1.7.0_51 x64 on Windows 8.1
I have the following SQL, which works perfectly:
select substr(to_char(tot_amount), 0, 1) as digit, count(*)
from transactions
where tot_amount <> 0
group by substr(to_char(tot_amount), 0, 1)
order by digit;
However, SQL Developer is yellow-underlining the first line, telling me that:
SELECT list is inconsistent with GROUP BY; amend GROUP BY clause to: substr(to_char(rep_tot_amount), 0, 1), substr(to_char(rep_tot_amount),
which is clearly wrong.
Message was edited by: JamHan
Added code formatting.Hello,
I also have found the same issue with the GROUP BY hint. Another problem I found is that the hint suggests to amend the GROUP BY members to add also constant values that are included in the SELECTed columns and whenever those constants include strings with spaces, it generates an invalid query. Normally, constant values won't affect grouping functions and as such they can be omitted from the GROUP BY members, but it seems SQL Dev thinks it differently.
For example, if you try the following query:
SELECT d.DNAME, sum(e.sal) amt, 'Total salary' report_title, 100 report_nr
FROM scott.emp e, scott.dept d
WHERE e.DEPTNO = d.DEPTNO
GROUP BY d.DNAME;
when you hover the mouse pointer on the yellow hint, a popup will show the following message:
SELECT list inconsistent with GROUP BY; amend GROUP BY clause to:
d.DNAME, 'Total, 100
If you click on the hint, it will amend the group by members to become:
GROUP BY d.DNAME, 'Total, 100;
that is clearly incorrect syntax. You may notice that after the change the yellow hint is still there, suggesting to amend further the GROUP BY members. If you click again on the hint, you will end with the following:
GROUP BY d.DNAME, 'Total, 100;
, 'Total, 100
and so on.
I am not sure if this behaviour was already known (Vadim??), but it would be nice if somebody could file a bug against it.
Finally when writing big queries with complex functions and constant columns, those yellow lines extend all over the select list and they are visually annoying, so I wonder if there is a way to disable the GROUP BY hint until it gets fixed.
Thanks for any suggestion,
Paolo -
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 -
Group by clause and having clause in select
hi frnds
plz give me some information of group by and having clause used in select statement with example
thanksThe Open SQL statement for reading data from database tables is:
SELECT <result>
INTO <target>
FROM <source>
[WHERE <condition>]
[GROUP BY <fields>]
[HAVING <cond>]
[ORDER BY <fields>].
The SELECT statement is divided into a series of simple clauses, each of which has a different part to play in selecting, placing, and arranging the data from the database.
You can only use the HAVING clause in conjunction with the GROUP BY clause.
To select line groups, use:
SELECT <lines> <s1> [AS <a1>] <s2> [AS <a2>] ...
<agg> <sm> [AS <am>] <agg> <sn> [AS <an>] ...
GROUP BY <s1> <s2> ....
HAVING <cond>.
The conditions <cond> that you can use in the HAVING clause are the same as those in the SELECT clause, with the restrictions that you can only use columns from the SELECT clause, and not all of the columns from the database tables in the FROM clause. If you use an invalid column, a runtime error results.
On the other hand, you can enter aggregate expressions for all columns read from the database table that do not appear in the GROUP BY clause. This means that you can use aggregate expressions, even if they do not appear in the SELECT clause. You cannot use aggregate expressions in the conditions in the WHERE clause.
As in the WHERE clause, you can specify the conditions in the HAVING clause as the contents of an internal table with line type C and length 72.
Example
DATA WA TYPE SFLIGHT.
SELECT CONNID
INTO WA-CONNID
FROM SFLIGHT
WHERE CARRID = 'LH'
GROUP BY CONNID
HAVING SUM( SEATSOCC ) > 300.
WRITE: / WA-CARRID, WA-CONNID.
ENDSELECT.
This example selects groups of lines from database table SFLIGHT with the value LH for CARRID and identical values of CONNID. The groups are then restricted further by the condition that the sum of the contents of the column SEATSOCC for a group must be greater than 300.
The <b>GROUP BY</b> clause summarizes several lines from the database table into a single line of the selection.
The GROUP BY clause allows you to summarize lines that have the same content in particular columns. Aggregate functions are applied to the other columns. You can specify the columns in the GROUP BY clause either statically or dynamically.
Specifying Columns Statically
To specify the columns in the GROUP BY clause statically, use:
SELECT <lines> <s1> [AS <a 1>] <s 2> [AS <a 2>] ...
<agg> <sm> [AS <a m>] <agg> <s n> [AS <a n>] ...
GROUP BY <s1> <s 2> ....
To use the GROUP BY clause, you must specify all of the relevant columns in the SELECT clause. In the GROUP BY clause, you list the field names of the columns whose contents must be the same. You can only use the field names as they appear in the database table. Alias names from the SELECT clause are not allowed.
All columns of the SELECT clause that are not listed in the GROUP BY clause must be included in aggregate functions. This defines how the contents of these columns is calculated when the lines are summarized.
Specifying Columns Dynamically
To specify the columns in the GROUP BY clause dynamically, use:
... GROUP BY (<itab>) ...
where <itab> is an internal table with line type C and maximum length 72 characters containing the column names <s 1 > <s 2 > .....
Example
DATA: CARRID TYPE SFLIGHT-CARRID,
MINIMUM TYPE P DECIMALS 2,
MAXIMUM TYPE P DECIMALS 2.
SELECT CARRID MIN( PRICE ) MAX( PRICE )
INTO (CARRID, MINIMUM, MAXIMUM)
FROM SFLIGHT
GROUP BY CARRID.
WRITE: / CARRID, MINIMUM, MAXIMUM.
ENDSELECT.
regards
vinod -
Why is the GROUP BY clause not working in my Query?
Dear All,
Below is the Query for a Summary Debtors Aged Analysis.
The GROUP BY clause does not seem to be working.
The Query returns all the unpaid invoices, instead of a single total row for each Customer.
If a Customer X has 10 unpaid invoices, 10 rows are displayed - one for each invoice.
I was expecting only 1 row for Customer X, 1 for Customer Y, etc.
This is what GROUP BY is supposed to do, but it is not doing its work.
What has gone wrong?
Thanks
Leon Lai
Here's my Query:
declare @taxdt datetime
set @taxdt
/*select 1 from jdt1 t0 where t0.TaxDate*/ = [%1]
SELECT
CASE
WHEN T0.Account = 1220101 THEN 'Prim Cust'
WHEN T0.Account = 1220102 THEN 'Fgn Cust'
WHEN T0.Account = 1220103 THEN 'Local Cust'
WHEN T0.Account = 1220104 THEN 'Staff Loan'
WHEN T0.Account = 1220105 THEN 'Dep with TP'
WHEN T0.Account = 1220106 THEN 'Adv to Cust'
WHEN T0.Account = 1220108 THEN 'Sund Drs'
ELSE 'Error ! ! !'
END AS 'Control A/c',
T1.CardCode AS 'BP Code',
T2.Notes2 AS 'BP Name',
SUM ((T0.Debit - T0.Credit)) AS 'Orig. Rs',
SUM ((T0.BalDueDeb - T0.BalDueCred)) AS 'Bal. Rs',
((SELECT SUM(T0.BalDueDeb) - Sum(T0.BalDueCred)
WHERE DateDiff(mm, T0.TaxDate, @taxdt) = 1))
AS '1 Mth Ago'
/* Similarly for other age brackets*/
FROM JDT1 T0
INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
LEFT OUTER JOIN OCPR T2 ON T1.CardCode = T2.Cardcode
LEFT OUTER JOIN OJDT T3 ON T0.TransID = T3.TransID
LEFT OUTER JOIN OINV T4 ON T3.TransID = T4.TransID
LEFT OUTER JOIN ORIN T5 ON T3.TransID = T5.TransID
WHERE
T1.CardType = 'C'
and (Balance) != 0
and (T0.BalDueDeb - T0.BalDueCred) != 0
GROUP BY T0.Account, T1.CardCode, T2.Notes2, T0.TaxDateDear Neetu,
Thanks for your reply.
This Query is a modification of the Query you posted in SAP B1 SQL TIPS & TRICKS
http://wiki.sdn.sap.com/wiki/display/B1/SAPB1SQLB-FNDebtorsAgingReportbydate
So, maybe instead of referring to my Query, let's refer to yours. It may be easier for you to understand me.
Once I understand the problem, I can adapt your query to suit my requirements
So, let's start with a clean slate:
The Query you have posted is for a DETAILED Debtors Aging Report.
This lists all outstanding invoices, and ages them in the Age Brackets.
What I want is a SUMMARY Debtors Aging Report.
This will give the total amount owed by each Customer, and this amount is broken down in the Age Bracket Columns
There will be a single row listed for each customer, something like this:
Customer Total Due Current 1 Mth 2 Mth 3 Mth etc
Alfred 500,000 300,000 200,000
Charles 800,000 100,000 300,000 400,000
How can you modify your query to make it become a Summary Report (1 line for each customer even if he has many invoices)?
Thanks
Leon Lai
Here's your code
SELECT T1.CardCode, T1.CardName, T1.CreditLine, T0.RefDate, T0.Ref1 'Document Number',
CASE WHEN T0.TransType=13 THEN 'Invoice'
WHEN T0.TransType=14 THEN 'Credit Note'
WHEN T0.TransType=30 THEN 'Journal'
WHEN T0.TransType=24 THEN 'Receipt'
END AS 'Document Type',
T0.DueDate, (T0.Debit- T0.Credit) 'Balance'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')<=-1),0) 'Future'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=0 and DateDiff(day, T0.DueDate,'[%1]')<=30),0) 'Current'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>30 and DateDiff(day, T0.DueDate,'[%1]')<=60),0) '31-60 Days'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>60 and DateDiff(day, T0.DueDate,'[%1]')<=90),0) '61-90 Days'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>90 and DateDiff(day, T0.DueDate,'[%1]')<=120),0) '91-120 Days'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=121),0) '121+ Days'
FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
WHERE (T0.MthDate IS NULL OR T0.MthDate > [%1]) AND T0.RefDate <= [%1] AND T1.CardType = 'C'
ORDER BY T1.CardCode, T0.DueDate, T0.Ref1
Maybe you are looking for
-
Font color problem upgrading from 1.3.1 to 1.4.2_02
I have noticed when we upgraded from 1.3.1 to 1.4.2_02 that JLabel font color is now black - it used to be blue. Does anyone know how to make the font color of JLabels revert back to the original blue without specifically calling setForeground() on e
-
VPLS and H-VPLS w.r.t Metro Ethernet
Can someone please explain me VPLS and H-VPLS as to how it can be used in a Metro Ethernet Environment????Any diagramatic explanation will be highly appreciable... Regards, NISHA
-
Conditional Build Tags Not Working
I'm using Robohelp X5 for Word but I just downloaded the trial version of Robohelp 7 and the same problem occurs. I'm trying to use condtional build tags to create 3 different help outputs from the same source file. The problem I'm having is sometime
-
Asssociating new Network to a ProjectDefinition
Hi, I am creating a new Network using 'BAPI_NETWORK_MAINTAIN' by using SE37 transaction. I am passing 'CREATE' and then 'SAVE' as Method parameter value in I_METHOD_PROJECT structure. I want to associate this network with some existing ProjectDefinit
-
How to change the email client for the 'Review' features. Acrobat Pro X
Acrobat Pro X (10.1.2) was installed on a system that used Lotus Notes (v8.5) email client, all was well. The system was then upgraded to MS Outlook 2010, so Outlook is now the email client on system. While reading a PDF document an email address c