我有2张桌子
标题表,
Id Name Value
1 Test1 Value1
2 Test2 Value2
评论表,
Id Comments comments_type CREATE_DTE
1 Testing CLOSE 03/15/2017
1 Testing RESEARCH 03/15/2017
1 Testing2 CLOSE 03/17/2017
2 Testing3 CLOSE 03/12/2017
2 Testing4 RESEARCH 03/16/2017
现在我已经为comments表编写了一个聚合查询,以根据ID合并行。
SELECT LISTAGG(COMMENTS, ';') WITHIN GROUP (ORDER BY CREATE_DTE DESC)
FROM COMMENTS_TBL GROUP BY ID
但是如何加入这两个表并获得所需的输出,
ID Name Value CLOSE_Comments Res_COMMENTS
1 Test1 value1 Testing2 ;Testing Testing
2 Test2 value2 Testing3 Testing4
答案 0 :(得分:3)
请在下面找到更新的查询。由于您已更改了我已进行更改的要求,因此在旧查询本身的顶部包含新列。
更新将INNER JOIN
替换为LEFT OUTER JOIN
以处理无评论方案
SELECT HEADER_TBL.ID
, HEADER_TBL.NAME
, HEADER_TBL.VALUE
, CLOSE_TYPE.CMTS CLOSE_CMTS
, RESEARCH_TYPE.CMTS RESEARCH_CMTS
FROM HEADER_TBL
LEFT OUTER JOIN (
SELECT ID
, LISTAGG(COMMENTS, ';') WITHIN GROUP (ORDER BY CREATE_DTE DESC) CMTS
FROM COMMENTS_TBL
WHERE COMMENTS_TYPE = 'CLOSE'
GROUP BY ID
) CLOSE_TYPE
ON HEADER_TBL.ID = CLOSE_TYPE.ID
LEFT OUTER JOIN (
SELECT ID
, LISTAGG(COMMENTS, ';') WITHIN GROUP (ORDER BY CREATE_DTE DESC) CMTS
FROM COMMENTS_TBL
WHERE COMMENTS_TYPE = 'RESEARCH'
GROUP BY ID
) RESEARCH_TYPE
ON HEADER_TBL.ID = RESEARCH_TYPE.ID;