需要帮助将多个列分组为一个

时间:2014-08-20 21:56:30

标签: sql db2

我在下面列出了我的查询以及我目前得到的结果。我想将“CLASS”列中的多个返回组合起来,只在可能的情况下返回一个值。

结果

SH DATE    NUMBER     CLASS
2014-7-1   123456     125
2014-7-1   123456     150

我希望将其视为

SH DATE    NUMBER     CLASS
2014-7-1   123456     125, 150

QUERY

SELECT 
DATE(B.TSTAMP) AS "SH DATE"
,TRIM(B.NUMBER) AS "NUMBER"
,CASE WHEN B.REPORT_TS IS NULL THEN '' ELSE CHAR(DATE(B.REPORT_TS)) END AS "DATE"
,F.CLASS AS "CLASS"
,S.CITY AS "ORIGIN CITY"
,S.STATE AS "ORIGIN STATE"
,S.ZIPCODE AS "ORIGIN ZIP"
,C.CITY AS "DESTINATION CITY"
,C.STATE AS "DESTINATION STATE"
,C.ZIPCODE AS "DESTINATION ZIP"
,B.WEIGHT

FROM AF.BLUE B

INNER JOIN AF.BILL F
ON F.NUMBER = B.NUMBER
AND F.CORRECTION = B.CORRECTION
AND F.CLASS <> ''

INNER JOIN AF.NAME S
ON S.NUMBER = B.NUMBER
AND S.CORRECTION = B.CORRECTION
AND S.TYPE = 'S'

INNER JOIN AF.NAME C
ON C.NUMBER = B.NUMBER
AND C.CORRECTION = B.CORRECTION
AND C.TYPE = 'C'

WHERE B.CUST = '11111'
AND (MONTH(CURRENT DATE)-1) = MONTH(B.TSTAMP)
AND B.CORR = ''

1 个答案:

答案 0 :(得分:1)

ListAgg文档

SELECT 
DATE(B.TSTAMP) AS "SH DATE"
,TRIM(B.NUMBER) AS "NUMBER"
,CASE WHEN B.REPORT_TS IS NULL THEN '' ELSE CHAR(DATE(B.REPORT_TS)) END AS "DATE"
,ListAgg(F.CLASS, ', ') WITHIN GROUP (Order by F.Class) AS "CLASS"
,S.CITY AS "ORIGIN CITY"
,S.STATE AS "ORIGIN STATE"
,S.ZIPCODE AS "ORIGIN ZIP"
,C.CITY AS "DESTINATION CITY"
,C.STATE AS "DESTINATION STATE"
,C.ZIPCODE AS "DESTINATION ZIP"
,B.WEIGHT

FROM AF.BLUE B

INNER JOIN AF.BILL F
ON F.NUMBER = B.NUMBER
AND F.CORRECTION = B.CORRECTION
AND F.CLASS <> ''

INNER JOIN AF.NAME S
ON S.NUMBER = B.NUMBER
AND S.CORRECTION = B.CORRECTION
AND S.TYPE = 'S'

INNER JOIN AF.NAME C
ON C.NUMBER = B.NUMBER
AND C.CORRECTION = B.CORRECTION
AND C.TYPE = 'C'

WHERE B.CUST = '11111'
AND (MONTH(CURRENT DATE)-1) = MONTH(B.TSTAMP)
AND B.CORR = ''

GROUP BY 
DATE(B.TSTAMP) 
,TRIM(B.NUMBER) 
,CASE WHEN B.REPORT_TS IS NULL THEN '' ELSE CHAR(DATE(B.REPORT_TS)) END 
,S.CITY 
,S.STATE 
,S.ZIPCODE
,C.CITY 
,C.STATE 
,C.ZIPCODE
,B.WEIGHT