db2,汇总case语句结果中的未知行数

时间:2018-01-12 11:48:21

标签: sql db2

我正在尝试编写一个查询,我可以根据DB2 v9.5中case语句的结果将某些行连接成一个列

contractId也可以是可变数量的行。

鉴于我有以下表结构

Table1
+------------+------------+------+
| ContractId | Reference  | Code |
+------------+------------+------+
| 12         | P123456789 | A    |
| 12         | A987654321 | B    |
| 12         | 9995559971 | C    |
| 12         | 3215654778 | D    |
| 13         | abcdef     | A    |
| 15         | asdfa      | B    |
| 37         | 282jd      | B    |
| 89         | asdf82     | C    |
+------------+------------+------+

我想得到结果的输出

+-------------+-----------------------+------------------------------------+
| ContractId  | Reference with Code A | Other References                   |
+-------------+-----------------------+------------------------------------+
| 12          | P123456789            | A987654321, 9995559971, 3215654778 |
| 13          | abcdef                | asdfa, 282jd, asdf82               |
+-------------+-----------------------+------------------------------------+

我尝试了像

这样的查询
select t1.contract_id,
max(case when t1.code = A then t1.reference end) as "reference with code a",
max(case when t1.code in ('B','C','D') then t1.reference end) as 'other references
from table t1
group by t1.contractId

然而,这仍然给我一个像

这样的输出
+-------------+-----------------------+------------------+
| ContractId  | Reference with Code A | Other References |
+-------------+-----------------------+------------------+
| 12          | P123456789            | null             |
| 12          | null                  | A987654321       |
| 12          | null                  | 9995559971       |
| 12          | null                  | 3215654778       |
+-------------+-----------------------+------------------+

我也尝试过使用一些XML Agg函数,但似乎无法按照我想要的方式进行格式化。

0 个答案:

没有答案