3

我在查询和分组时遇到问题。

我需要以下输出:

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 产生错误:

[DB2 for i5/OS]SQL0122 - SELECT 列表中的列 SNAME 或表达式无效。

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
4

1 回答 1

5

GROUP BY GROUPING SETS是一个用于分组/立方体数据的强大工具。它允许您将非聚合数据与聚合数据组合在一个查询结果中。

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

来自 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

这导致:

  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
于 2012-04-16T22:04:33.237 回答