简体   繁体   中英

DB2 SQL SUM and GROUPING

I am having problems with querying and grouping.

I am needing the following output:

officr, cbal, sname  
ABC, 500.00, TOM JONES  
ABC, 200.00, SUE JONES  
ABC TOTAL 700.00  

RAR, 100.10, JOE SMITH  
RAR, 200.05,  MILES SMITH  
RAR TOTAL 300.15  

SQL below produces the error:

[DB2 for i5/OS]SQL0122 - Column SNAME or expression in SELECT list not valid.

SELECT
    lnmast.officr,  SUM(LNMAST.CBAL), lnmast.sname
FROM
    LNMAST
WHERE LNMAST.RATCOD IN (6,7,8) AND STATUS NOT IN ('2','8')
group by lnmast.officr

GROUP BY GROUPING SETS is a POWERFUL tool for grouping/cubing data. It lets you combine non-aggregated data with aggregated data in one query result.

SELECT lnmast.officr,  SUM(LNMAST.CBAL), lnmast.sname
FROM LNMAST
WHERE LNMAST.RATCOD IN (6,7,8) 
  AND STATUS NOT IN ('2','8')
GROUP BY GROUPING SETS ((lnmast.officr, lnmast.sname),(lnmast.officr))

An example from IBM DOCS: www.ibm.com/support/knowledgecenter/en/... :

  SELECT WEEK(SALES_DATE) AS WEEK,
         DAYOFWEEK(SALES_DATE) AS DAY_WEEK,
         SALES_PERSON, SUM(SALES) AS UNITS_SOLD       
  FROM SALES 
  WHERE WEEK(SALES_DATE) = 13
  GROUP BY GROUPING SETS ( (WEEK(SALES_DATE), SALES_PERSON),
                           (DAYOFWEEK(SALES_DATE), SALES_PERSON))
  ORDER BY WEEK, DAY_WEEK, SALES_PERSON

This results in:

  WEEK        DAY_WEEK    SALES_PERSON    UNITS_SOLD 
  ----------- ----------- --------------- -----------
           13           - GOUNOT                   32
           13           - LEE                      33
           13           - LUCCHESSI                 8
            -           6 GOUNOT                   11
            -           6 LEE                      12
            -           6 LUCCHESSI                 4
            -           7 GOUNOT                   21
            -           7 LEE                      21
            -           7 LUCCHESSI                 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM