Select columns not in group by clause
Hi Guys,
I want to fetch columns from a table which are not in group by clause. The catch here is that I also need a count and decode column..
SELECT col_A, col_B, decode(col_C, '10', '10', '26', '26', '00') col_CT, col_X, col_Y count(*) CNT
FROM TABLE_T
WHERE col_B IN (100,101,102) AND col_C IN ('44','45','10','26')
GROUP BY col_A, col_B, decode(col_C, '10', '10', '26', '26', '00')
ORDER BY col_CT
Since, col_X and col_Y are not in GROUP BY clause, it throws error. Also, decode/count of the columns makes it more complex.
Please help me on this.
Thanks,
Amy
Hi, Amy,
Welcome to the forum!
Whenever you have a problem, post a little sample data (CREATE TABLE and INSERT statments, relevant columns only) for all tables involved, and the results you want from that data.
Always say which versionof Oracle you're using.
How to do what youy want depends on what you want, which is unclear.
If you say "GROUP BY a, b, c", that means you only want one row of output for each distinct combination of a, b and c. How do x and y fit into that? Do you want a separate output row for each distinct combination of a, b,c, x and y? Then add x and y to the GROUP BY clause. If you don't want separate rows for each combinataion of x and y, what do you want when a group has more than 1 value for either of them?
You can simplify the code a little by doing the DECODE in a sub-query; then you can use the alias col_ct as many times as you like in the main query. That will make the code easier to maintain, too.
Similar Messages
-
More than 1 column in the group by clause
DB Version:10gR2
I understand the basics of GROUP BY clause. I have a question on why we have on more than 1 columns in GROUP BY clause.
In the below example, the course name by itself does not make up a group. A Course name plus its BeginDate make up a group. This is the whole point of having more than 1 columns in the GROUP by clause. Right?
SQL> select r.course, r.begindate , count(r.attendee) as attendees
3 from registrations r
4 group by r.course, r.begindate
5 order by course
6 /
COURSE BEGINDATE ATTENDEES
JAVA 12/13/1999 5
JAVA 2/1/2000 3
OAU 8/10/1999 3
OAU 9/27/2000 1
PLS 9/11/2000 3
SQL 4/12/1999 4
SQL 10/4/1999 3
SQL 12/13/1999 2
XML 2/3/2000 2ExpansiveMind wrote:
Thanks Dmorgan. I am just learning the basics of GROUP BY clause. I have noticed that all Non-aggregate columns in SELECT list have to be present in the GROUP BY clause. I thought it was a "syntactical requirement". Now, i realise that these columns are present in the GROUP BY clause because only a combination of columns make up a group.Well, it is a bit of both actually. It is a syntactic requirement that all non-aggregated columns in the select list must appear in the group by clause. However, the non-aggregated columns in the select list is what defines your group. Your two examples define two different groups, and would answer two different questions.
John -
How to use single column in a group by clause
hi frs
i hve used sum function in a sql how to use a single column in a query.
for ex
select sum(sal),ename,job,deptno,empno from emp
group by deptnowhether its possible to use single column in a group by class.
i want like this because in my custom report i need it. Report query has more than 30 column so its not possible to use 30 columns in a group by.
pls help.
Thanks
RajeshMaybe something like this -
Select ename, job, deptno, empno, sal, col1, col2, col3, col4 ......, coln
From
Select SUM(sal) sal, deptno deptno_i
From Emp
Group By deptno
,Emp
Where deptno = deptno_i
Shailender Mehta -
How to display column specified in group by clause only once?
I've a result coming out of a sql query that uses group by clause as follows:
2008-07-25 19" LCD Screen 5
2008-07-25 HP Printer 4
2008-08-01 Hanging Files 11
2008-08-01 Stapler 3
2008-08-15 19" LCD Screen 5
2008-08-15 Hanging Files 14
What should I do in the query to display the result set as follows:
2008-07-25 19" LCD Screen 5
HP Printer 4
2008-08-01 Hanging Files 11
Stapler 3
2008-08-15 19" LCD Screen 5
Hanging Files 14Hi,
That's a display issue, and display issues are best handled by the front end.
What is your frone end?
If it's SQL*Plus, you can use the BREAK command.
For example:
BREAK ON deptno NODUPLICATES
SELECT deptno
, ename
FROM scott.emp
ORDER BY deptno
, ename
;Output:
` DEPTNO ENAME
10 CLARK
KING
MILLER
20 ADAMS
FORD
JONES
SCOTT
SMITH
30 ALLEN
BLAKE
JAMES
MARTIN
TURNER
WARDNote that deptno is never NULL: KING and MILLER have deptno=10; but it doesn't show in the display, because it's the same as the deptno on the previous row.
NODUPLICATES is actually the default, so you could just say
BREAK ON deptnoThe BREAK command remains in force until you end the session (or un-do it, e.g. with "CLEAR BREAKS")
Remember to issue the BREAK command at least once in the session before running the query.
To get the same results in SQL, use the analytic ROW_NUMBER function. -
Qry with non aggregate cols and not in group by clause too.
Hi all,
This is the table.
PROFILE_ID_NO WORK_OK_CD CREATE_DT
7041086 Y 2003-10-07-10.56.42
7041086 Y 2003-10-05-10.56.42
7041086 null 2003-10-06-06.58.08
7041086 N 2004-09-30-05.08.22
I want a qry to pick a profile_id_no and work_ok_cd where create_dt is maximum. I tried
select profile_id_no, work_ok_cd , max(create_dt) from profile group by profile_id_no, work_ok_cd
It gave 3 rows . I dont want that.
I want only the last row to be displayed. How to do that?
Pls help me write this qry .
Thanks
Jayauser13743192 wrote:
I want a qry to pick a profile_id_no and work_ok_cd where create_dt is maximum.
...Setup:
create table profile (
PROFILE_ID_NO number
, WORK_OK_CD varchar2(1)
, CREATE_DT date
alter session set nls_date_format = 'YYYY-MM-DD-HH.MI.SS';
insert into profile values (7041086, 'Y', '2003-10-07-10.56.42');
insert into profile values (7041086, 'Y', '2003-10-05-10.56.42');
insert into profile values (7041086, null, '2003-10-06-06.58.08');
insert into profile values (7041086, 'N', '2004-09-30-05.08.22');
commit;What if there is another row that ties the maximum CREATE_DT?:
insert into profile values (9999999, 'Y', '2004-09-30-05.08.22');Would you want all rows that match the maximum or only one. If you want all rows, maybe use?:
SQL> select PROFILE_ID_NO, WORK_OK_CD, CREATE_DT
2 from PROFILE
3 where CREATE_DT = (select max(CREATE_DT) from PROFILE);
PROFILE_ID_NO W CREATE_DT
7041086 N 2004-09-30-05.08.22
9999999 Y 2004-09-30-05.08.22Otherwise, use one of Frank Kulash's queries above, although the first query (using "DENSE_RANK") gives:
PROFILE_ID W CREATE_DT
9999999 Y 2004-09-30 05:08 amand the second gives:
PROFILE_ID_NO W CREATE_DT
7041086 N 2004-09-30-05.08.22 -
Why selected columns not show all in result output?
in the analysis, i select 4 columns but only 3 show up, why?
Is that pivot table? Check ex lured section of the same.
Need more info your before or after steps done. -
Columns not to be included in group by clause
I have a select query where i need to display count of records group by state_name
In my main select query i need to include two more columns which are not be included in group by clause so that the number of records displayed does not increase
I need to pass all these values from front end application so that i get count of records only by statename
But when i include these two columns in my select query my query is throwing an error bcoz i have not included them in my group by
How can we prevent this by not adding it to group by clauseOne general approach is (using the emp dept example)
I want
deptno dname, count(distinct empno)
I can do that
select d.deptno, d.dname, count(distinct e.empno)
from dept d, emp e
where e.deptno=d.deptno
group by d.deptno, d.dname;
or
select d.deptno, d.dname, count_emp
from dept d,
(select e.deptno, count(distinct empno)
from emp e
group by e.deptno
where d.deptno = e.deptno
or depending on version (you don't mention versionk, though most questions have version dependent answers)
select deptno
, dname
, (select count(distinct empno) from emp e where e.deptno=d.deptno)
from dept d
Obviously you can also use the FIRST and the LAST function to avoid having to include a column in the GROUP BY clause.
Sybrand Bakker
Senior Oracle DBA -
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 -
I wrote the view in the Original View section below. I query it with the following SELECT statement:
SELECT *
FROM ZZBUD_DEBT_SERVICE_V
WHERE action_month IN ('01','02')
AND action_year IN ('2011')
AND short_name IN( 'WHIT-18','2REDFERN')
ORDER BY action_year,action_month, group1, group2, short_name;
An get these results:
SHORT GROUP1 GROUP2 ACTION ACTION CURR CURR CURR
NAME YEAR MONTH INT INT PRIN
ACCRUED PAYMENT PAYMENT
2REDFERN 05 02 2011 01 149.39 0 0
2REDFERN 05 02 2011 02 0 896.32 49795.84
WHIT-18 05 01 2011 01 442.86 0 0
WHIT-18 05 01 2011 02 442.86 2657.14 0
I need to compute the year-to-date CURR_INT_ACCRUED, CURR_INT_PAYMENT, CURR_PRIN_PAYMENT (SUM(CURR_INT_ACCRUED), etc.) by short_name and action_year but I can't tweek my GROUP BY statement properly. What would the GROUP BY expression look like to get the sum of these columns?
Original View:
CREATE OR REPLACE VIEW ZZBUD_DEBT_SERVICE_V(short_name, group1, group2, action_year, action_month
, curr_int_acrrued, curr_int_payment, curr_prin_payment)
AS
SELECT short_name, group1, group2, action_year, action_month
, SUM(curr_int_acrrued) curr_int_acrrued
, SUM(curr_int_payment) curr_int_payment
, SUM(curr_prin_payment) curr_prin_payment
FROM (
SELECT dsa.short_name
, dsa.group1
, dsa.group2
, dsa.action_year
, dsa.action_month
, DECODE(SIGN(dsa.int_accrued),-1,0 ,0,0,dsa.int_accrued) curr_int_acrrued
, DECODE(SIGN(dsa.ytd_accrued),1,0,0,0,ABS(dsa.ytd_accrued)) curr_int_payment
, DECODE(SIGN(dsa.bond_outstand),1,0,0,0,ABS(dsa.bond_outstand)) curr_prin_payment
FROM NYC.ZZBUD_DEBT_SERVICE_MASTER DSA
WHERE dsa.bond_status = 'A'
AND dsa.group1 IN ('03', '05', '06', '07')
ORDER BY dsa.group1, dsa.group2, DSA.short_name, dsa.action_year, dsa.action_month
GROUP BY short_name,group1,group2,action_year,action_monthIt depends on how you look at it. When I issue the command:
SELECT group1, group2, short_name,SUM(curr_int_acrrued) ytd_accrued_int
FROM ZZBUD_DEBT_SERVICE_V
WHERE action_month IN ('01','02')
AND action_year IN ('2011')
AND short_name IN ('BXRIVER','WILSON','WHIT-18','2REDFERN')
GROUP BY action_year,action_month,group1, group2, short_name
ORDER BY action_year,action_month, group1, group2, short_name
I'm not getting the results I want as 'WHIT-18' shows detail for both action_months and I want the SUM of 01 & 02 and the same for the other short_names. When I drop columns from the GROUP BY clause I get error ORA-0979 'Not a GROUP BY expression'. -
Do I need all of these group by clauses?
Hello!
I'm generating an invoice from a database I've created as part of my University assignment and this query seems to answer the question
"10. For a child of your choice calculate the invoice for a month. You must display the name of the child, name of their parent, address details and Month and Year of the invoice, and the total amount to pay. "
select '£' || SUM(s.rate) Total, c.f_name || ' ' || c.l_name Child_Name, c.house_n, c.street, c.city,
c.postcode, p.f_name || ' ' || p.l_name Parent_Name, '04-11' "Generated"
from sessions s, child_register cr, child c, parents p
where s.session_id = cr.session_id
and p.parent_id = c.parent_id
and cr.child_id = c.child_id
and cr.child_id = 'C110001'
and s.sdate BETWEEN '01-APR-11' and '30-APR-11'
group by c.l_name, c.f_name, c.l_name, c.f_name, c.house_n, c.street, c.city, c.postcode, p.f_name, p.l_name;I'm wondering, is there a better way than having all those columns in my group by clause? If I remove any I get "not a group by function" errors.
Thanks for any advice!
MikeHi, Mike,
You can do the aggregations separately, in a sub-query, and then join that result set to the other tables, something like this:
WITH session_summary AS
SELECT session_id
, SUM (rate) AS total_rate
FROM sessions
WHERE sdate BETWEEN TO_DATE ( '01-APR-2011' -- Don't compare a DATE to a string
, 'DD-MON-YYYY'
AND TO_DATE ( '30-APR-2011'
, 'DD-MON-YYYY'
GROUP BY session_id
SELECT '£' || s.total_rate AS total
, c.f_name || ' '
|| c.l_name AS Child_Name
, c.house_n
, c.street
, c.city
, c.postcode
, p.f_name || ' '
|| p.l_name AS Parent_Name
, '04-11' AS Generated
FROM session_summary s
, child_register cr
, child c
, parents p
WHERE s.session_id = cr.session_id
AND p.parent_id = c.parent_id
AND cr.child_id = c.child_id
AND cr.child_id = 'C110001'
;This assumes that, aside form the sessions table, there is a one-ro-one relationsheip between the tables.
If you'd post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and the results you want from that data (formatted, between \ tags) then I could test it.
Always say what version of Oracle you're using. -
I have one SQL query using a GROUP BY clause and no ORDER BY clause is used. When executed in Oracle 8i, the query results are returned ordered by first column mentioned in the GROUP BY clause. When the same query is executed in Oracle 10g, the query results are returned withour ordering the data by the first column in the GROUP BY clause. It works only when I explicitly mention the ORDER BY clause. Can you please explain this? In Orcale 8i, is it that, by default, the data is ordered by the first column mentioned in the GROUP BY clause when ORDER BY clause is not mentioned?
In which order does oracle 10g sorts when I use group by clause in oracle 10g[email protected] wrote:
the use of group by is to group based on some column value, in this case why does the the output differs in rows. why does the output, when you use group by is not the following formatSorry, but this is a totally fruitless topic. Why are you bothering with something that is totally internal to the DBMS? If you want the data ordered, use ORDER BY, it's that simple.
Check out this link, if you want some discussion on it:
[http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:74320098178823] -
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. -
Text select tool not working properly
When I use the text select tool, it selects columns, not words in a row, which is what I want. It used to work correctly. I am using Acrobat Pro, version 9.0.0.
I tried adding the ALT key, with no good result.Is it with this specific document o any pdf you work on?
If it was earlier working fine for you, try repairing Acrobat by going to 'Help' menu > Repair Acrobat.
Also make sure you have updated it to the latest patch.
Regards,
Ravi. -
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$_"}}) -
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
-
Audio Recording, from Mic to computer
Good Peoples, I thought that plugging a mic into the mini port on the computer would work for using and external mic. I switched from internal to external in under system preferences but nothing is picked up. The internal mic works. Anyone know about
-
Internet signal but no Windows XP internet connection
I have a MacPro partitioned using BootCamp and can access the internet using the Mac OS side but when I open to the Windows XP partition, I have an "excellent" signal denoted in the lower right hand corner but can not get a connection to the internet
-
Need some help logic keeps crashing
here is my error report i would really like to keep working on this project as its weeks worth of time ive spent on it any help will be appreciated my problem first started when i hit the reorganize memory button in song information, it told me i had
-
SXMB_MONI is not showing any messages flow
Hi, I am sending a request through SOAP adapter to SAP system. My scenario is executing fine. One strange thing I have seen is, in RWB, Message Monitoring I can see my outbound message and inbound message but in component monitoring I cannot see my S
-
Oracle.jbo.TooManyObjectsException
Hi all, I know this error has been already discussed here. I want to know all the scenarios which can produce this error. My scenario is : When am trying to create a row in VO using vo.create it gives this error.I dint even execute the query.Jdev Log