Group by clause issue

Hi all,
i am having some issue in grouping columns i have some specific criteria depending on that i need to group columns.
i have table as transaction_table in that i have
Transaction item prom_id
296     A     null sale     -- prom --Source item
296     B     1 sale     -- prom --Target item
296 A null
298     A null
promotin
prom_id id_ru_prd     
1 123
2 345
source_base
id_ru_prdv item
123 A
345 B
in above table for transaction 296 i have item A twice but out of them one item is sold in promotion with target item B and other is non promotional item A.
i have prom_id which tells me which target item is sold in promotion but to find out source item (in this example item A) i have column in other base table(promotion table) which tells me associated source item using prom_id
i need to calculate sum of quantity depending weather item was sold in promotion or not
result should be
item quantity promotion / non promotional
A 1 promotion
B 1 promotion
A 2 non promotional
in group by it doesn't allow sub query , can anyone help me on this pls?

I'm having a hard time understanding what you are trying to do.
Can you write what you want in SQL, and then we'll see if we can get the same result in XQuery?
I think what you want is the union of :
select trans, count(*) from transaction_table group by trans where prom is null
select trans, count(*) from transaction_table group by trans where prom is not null
Edited by: mikereiche on Jul 7, 2011 4:11 PM

Similar Messages

  • COUNT with Group By clause issue

    Good Morning everyone. I have a simple query that calculates the count of 3 expressions. It is supposed to group by region and province as a result set, but instead places the TOTAL count for each expression in the region and province fields. What am I doing wrong? This is my query:
    SELECT TABLE1."Province",
    TABLE1."Region",
    (SELECT(COUNT(TABLE1."Nationality"))
    FROM TABLE1
    WHERE (TABLE1."Nationality" <> 'United States'
    AND TABLE1."Nationality" <> 'Nat1')
    OR (TABLE1."Medical" <> 'ON MEDICAL'
    AND TABLE1."Region" <> 'CONUS')
    ) "TCN COUNT",
    (SELECT(COUNT(TABLE1."Nationality"))
    FROM TABLE1
    WHERE (TABLE1."Nationality" = 'United States')
    OR (TABLE1."Medical" <> 'ON MEDICAL'
    AND TABLE1."Region" <> 'CONUS')
    ) "US COUNT",
    (SELECT(COUNT(TABLE1."Nationality"))
    FROM TABLE1
    WHERE (TABLE1."Nationality" = 'Nat1')
    OR (TABLE1."Medical" <> 'ON MEDICAL'
    AND TABLE1."Region" <> 'CONUS')
    ) "HCN COUNT"
    FROM TABLE1
    GROUP BY TABLE1."Province",
    TABLE1."Region";
    Any help would be appreciated. Thank you.
    Aqua

    Because you are not passing any values to the inner query from the outer one..
    Are you looking for this?
    SELECT      TABLE1."Province",
         TABLE1."Region",
         sum (
           case when (
                 TABLE1."Nationality" != 'United States'
                 AND TABLE1."Nationality" !=  'Nat1'
                OR (
                TABLE1."Medical" != 'ON MEDICAL'
                AND TABLE1."Region" != 'CONUS'
                 ) then 1 else 0 end
             ) "TCN COUNT",
         sum (
           case when (
                TABLE1."Nationality" = 'United States'
                OR (
                TABLE1."Medical" 'ON MEDICAL'
                AND TABLE1."Region" 'CONUS'
                   ) then 1 else 0 end
             ) "US COUNT",
         sum (
           case when (
                TABLE1."Nationality" = 'Nat1'
                  OR (
                   TABLE1."Medical" 'ON MEDICAL'
                   AND TABLE1."Region" 'CONUS'
                     ) then 1 else 0 end
             ) "HCN COUNT"
    FROM TABLE1
    GROUP BY TABLE1."Province",TABLE1."Region";

  • Issue in group by clause.

    Hi,
      I am using a select query to retrieve sum of few numeric fields as below.
    select field1 field2
             sum ( field3 ) as field3
             sum ( field4 ) as field4
    into table t_tab1
    from dbtab
    where field1 in s_field1
    and   field2 in s_field2
    and   field <> 'RNIC'
    group by field1 field2.
    above code while syntax check gives error stating field 'RNIC' is missing in group by.
    When I remove group by, program gives a short dump.
    Please help me in resolving this issue.
    Thanks in advance.
    Suresh.

    Hi Rich,
       I am using equals opereator in the select query, if I remove the group by clause, no syntax errors appears but program gives dump saying the table mentioned in from clause does not have any field by 'SUM'. However if I mention group by clause it gives syntax error,
    please suggest....
    Suresh.
    this is my select query.
      SELECT rcomp racct robukrs
             sum ( tslvt ) AS tslvt
             sum ( tsl01 ) AS tsl01
             sum ( tsl02 ) AS tsl02
             sum ( tsl03 ) AS tsl03
             sum ( tsl04 ) AS tsl04
             sum ( tsl05 ) AS tsl05
             sum ( tsl06 ) AS tsl06
             sum ( tsl07 ) AS tsl07
             sum ( tsl08 ) AS tsl08
             sum ( tsl09 ) AS tsl09
             sum ( tsl10 ) AS tsl10
             sum ( tsl11 ) AS tsl11
             sum ( tsl12 ) AS tsl12
        FROM (w-tabnm)  CLIENT SPECIFIED
        INTO TABLE t_zzallt
         WHERE rclnt   EQ syst-mandt
         AND rcomp     IN s_rcomp
         AND racct     IN s_saknr
         AND racct     IN aoacct_range
         AND ( rcomp  NOT IN aononk4rcomp_range )
         AND ryear     EQ p_year
         AND  ( ( rldnr = 'PS' AND rcomp  NOT IN aopsrcompx_range ) OR
                ( rldnr  NOT IN ao_ledgerx_range ) )
       GROUP BY rcomp racct robukrs.

  • Query Plan 'group-by' clause

    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,
    PB

    is 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>

  • Right GROUP BY clause

    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_month

    It 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'.

  • Group by Perfromance issue with Number and Varchar2

    Hi All,
    I got a question on performance on GROUP BY clause.
    Group by (Number) and Group by (Varchar2) --> In these 2 versions of Group by will oracle takes into consideration for the data types in the GROUP BY Clause as a performance issue.
    I.E. Select sum(sal) from emp group by deptno and Select sum(sal) from emp group by job.
    In the first group by we have number and second we got varchar2. So oracle will take the data types also into consideration for performance in the Group by clause.
    (Pls dont consider the amount of data in the tables ).
    Appreciate your response,
    Thanks,
    Madhu K.

    You are asking which way is more efficient?
    if someone ask to do a group by using a varchar column. oracle has no other way to do it but by the columns that the developer asks for...
    Amiel

  • Output not sorted when using group by clause

    Recently we migrated our application from Forms5 to Forms10g and database from 7.3.2 to 10gR2.
    More than 400 applications using sql stmt with "group by" clause and without "order by".
    In Earlier version of oracle 7.3.2 "group by" clause in SQL stmt sorts the output by order of the column in the "group by"
    stmt, where new version of oracle 10g (10.2.0.1.0 - 64bit Production) doesnt behave like older version.
    eg select div_cd,dept_cd,count(*) from class group by div_cd,dept_cd
    Output of the above query in Oracle7
    DIV_CD DEPT_CD COUNT(*)
    0 1     120
    0 9 131
    1 4 938
    1 6 1
    4 1 1490
    5 2 59
    6 6 848
    6 9 295
    8 1 45
    9 5 19
    Output of same query in Oracle10g
    DIV_CD DEPT_CD COUNT(*)
    0 6 120
    0 9 131
    4 1 1490
    6 9 295
    8 1 45
    9 5 19
    1 4 938
    1 6 1
    5 2 59
    6 6 848
    My question is
    a) Does the oracle behave in that manner?.
    b) if so, Any patch set available for this?
    c) if no patch set how to resolve this issue.
    if i use "order by" clause
    along with group by then i can get the output how i want.
    BUt problem is more than 400 applications (forms) using above method.
    Identify Forms/Reports and rectifing is a tedious job.
    Anyone can give me a good solution to solve the above issue

    Group By does not, and never has guaranteed order. Just because it happened that way on the past does not mean it will continue to do so.
    In the past, the algorithm used for Group By invoked a sort. It was convenient for the system to simply dump the output in that resulting order. These days, Group By could also be accomplished using a hash algorithm. Walking through the hash can easily result in a completely different ordering, as you have seen.
    Your problem is that the assumptions made previously are now invalid. Oracle is still working correctly. No patch, but you might be able to work around it by crippling your database and using the COMPATIBLE parameter (although the official lower limit is 9.2.0)

  • 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.
    Sheen

    Hi,
    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

  • GROUP BY clause diff in Sybase and Oracle

    Hi,
    I am migrating code from Sybase to Oracle and came across a strange issue which is widely known to others :)
    In Sybase , one can use columns or calculations in the SELECT expressions that don't appear
    in the GROUP BY clause of the query. Like
    SELECT order.custid,customer.name,MAX(payments)
    -> FROM order, customer
    -> WHERE order.custid = customer.custid
    -> GROUP BY order.custid;
    works fine but for SQL we need to add customer.name to GROUP BY clause.
    On the similar lines, here is my SQL query
    INSERT INTO GTT_CTRT_recalc_proc
    (id_fin_rec,
    id_imnt,
    id_instr_opn,
    dt_instr_opn,
    dt_opn,
    dt_cls_loanet,
    dt_prcss,
    am_invst)
    SELECT t1.id_fin_rec,
    t1.id_imnt,
    t1.id_instr_opn,
    t1.dt_instr_opn,
    t1.dt_opn,
    NVL(t1.dt_cls_loanet, l_dt_to),
    t1.dt_prcss,
    SUM(t2.am_invst) + (0.123 * (1 - abs(sign(0 - SUM(t2.am_invst)))))
    FROM GTT_CTRT_TEMP_recalc_process t1, GTT_CTRT_TEMP_recalc_process t2
    WHERE t2.id <= t1.id
    AND t2.id_imnt = t1.id_imnt
    AND t2.id_instr_opn = t1.id_instr_opn
    AND t2.dt_instr_opn = t1.dt_instr_opn
    GROUP BY t1.id_imnt,
    t1.id_instr_opn,
    t1.dt_instr_opn,
    t1.dt_opn,
    t1.dt_cls_loanet,
    t1.dt_prcss;
    Which does not have t1.id_fin_rec in GROUP BY failing it in SQL.
    I know that if I add this column in GROUP BY it will work fine but I am told to keep the functionality as it is as the result before and after adding the column would be diff of-course.
    Please guide me about what can be done in this situation and is there any work around for this?
    Thanks,
    Aashish

    That's a piece of nasty denormalisation. We shoudl also expect trouble we do stuff like that. Anyway, I think encapsulating the stuff from T2 into an inline view should sort you out....
    INSERT INTO GTT_CTRT_recalc_proc
    (id_fin_rec,
    id_imnt,
    id_instr_opn,
    dt_instr_opn,
    dt_opn,
    dt_cls_loanet,
    dt_prcss,
    am_invst)
    SELECT t1.id_fin_rec,
    t1.id_imnt,
    t1.id_instr_opn,
    t1.dt_instr_opn,
    t1.dt_opn,
    NVL(t1.dt_cls_loanet, l_dt_to),
    t1.dt_prcss,
    , t2.total
    FROM GTT_CTRT_TEMP_recalc_process t1
        , ( select id_imnt,
                    id_instr_opn,
                    dt_instr_opn,
                    SUM(am_invst) + (0.123 * (1 - abs(sign(0 - SUM(am_invst))))) AS total
            FROM GTT_CTRT_TEMP_recalc_process
           GROUP BY  id_imnt,
                           id_instr_opn,
                           dt_instr_opn ) t2
    WHERE t2.id <= t1.id
    AND t2.id_imnt = t1.id_imnt
    AND t2.id_instr_opn = t1.id_instr_opn
    AND t2.dt_instr_opn = t1.dt_instr_opn
    GROUP BY t1.id_imnt,
    t1.id_instr_opn,
    t1.dt_instr_opn,
    t1.dt_opn,
    t1.dt_cls_loanet,
    t1.dt_prcss;Cheers, APC
    blog: http://radiofreetooting.blogspot.com
    Edited by: APC on Mar 16, 2009 2:31 PM
    Forgot to include GROUP BY in the inline view

  • CFQUERYPARAM tag not working in GROUP BY clause

    I am getting an error whenever I put a CFQUERYPARAM tag in a
    GROUP BY clause. I saw on another message board someone was having
    a similar problem with the ORDER BY clause
    Here is a sample of what my code might look like
    select x, y, z from abc
    group by <cfqueryparam value="x"
    cfsqltype="cf_sql_float">
    Here is the error I receive.
    Error Executing Database Query.
    [Macromedia][Oracle JDBC Driver][Oracle]ORA-00979: not a
    GROUP BY expression
    Any insight?

    The cachedwithin and cachedafter functions store the query
    results in the server's RAM. That means, while it's cached,
    whenever you run it, you get the cached result instead of going to
    the database to run it again. This increases speed of course, but
    if the data changes during the cache period, you have accuracy
    problems.
    It does not create memory issues. In the administrator you
    reserve a certain amount of memory for query caching. If you exceed
    that amount, the last query in pushes the first query out, or
    something like that.
    With regards to what you are trying to do about binding
    variables in your group by clause, that's not what cfqueryparam was
    designed for. It was designed for
    where clauses (where this = <cfqueryparam etc>
    or insert queries (insert into my table (field) values
    (<cfqueryparam>
    and things like that.
    You are trying to use it for something other than what it was
    designed for, which explains why it's not working for you.

  • 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

  • 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 14

    Hi,
    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.

  • 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.TaxDate

    Dear 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

  • 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,
    Regards

    I 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

Maybe you are looking for

  • Edi inbound order

    dear all i created sales order with the help of inbound idoc and order is created in the system..but i want see the idoc(inbound) from my sales order..not in we02 or we05 i searched VA03 there is field called SERVICE FOR OBJECT...but it is saying no

  • Fax Machines Obsolete?

    My old Brother fax machine finally broke but with new technological advances I am not sure if I should replace it with another traditional machine, or is sending a fax via the computer extremely common and easy now? The main reason I would need a fax

  • How to update Device location notes

    Hi Guys, I am getting an inbound idoc which is same as ISU_MR_UPLOAD01 and using the MRID number I need to update the device location notes. Could you please let me know if you have any idea on this. Thanks, Sar

  • How to stream iTunes videos without storing them on AppleTV or iPod?

    I have several iTunes high res videos (very large files) that I would like to stream to my AppleTV, but not store them on the AppleTV or iPod. How do I mark these videos in iTunes so this happens while still allowing other videos to be stored locally

  • Search KM resources involved in approval process

    Hi all, I would like to know if there is any way to search documents not published in SAPKM through TREX or some feature better than a deep search through the collection hierarchy using SAPKM APIs. The last approach is very CPU time and RAM consuming