Select ID,LISTAGG(CATEGORY_CD, ',') WITHIN GROUP(ORDER BY CAST(P_NO as INT)) AS CATEGORY_CD
FROM table1
WHERE DATE = '2022-02-02'
AND CATEGORY_FLAG = '0'
AND CAT_SRC_CD NOT IN ('0','1','2','3')
group by ID
我需要重写上面的查询,这样它应该是 ORDERED BY P_NO 并且我需要为 CATEGORY_CD 列显示不同的值。
我尝试了下面提到的逻辑,并在子查询中使用了 ORDER BY P_NO。不知道我写的逻辑是否正确。
SELECT ID,LISTAGG(distinct CATEGORY_CD, ',') WITHIN GROUP(ORDER BY CAST(CATEGORY_CD as INT)) AS CATEGORY_CD
FROM
(SELECT distinct ID,CREATE_DT,CATEGORY_CD,
TRY_CAST(P_NO as INTEGER) as P_NO
FROM table1
WHERE DATE = '2022-02-02'
AND CATEGORY_FLAG = '0'
AND CAT_SRC_CD NOT IN ('0','1','2','3')
ORDER BY P_NO
)
GROUP BY
ID;
我提到的原始查询给出了以下结果。我应该只显示 CATEGORY_CD 列的不同值,结果应该是 ORDERED BY P_NO 列。
ID CATEGORY_CD
169174408 5,5,5,5
169174408 2,1,1
169174408 12,12,12,12,12,12
839946105 2,2,2,2,3,3,3,3,3,3,3,3
请指导我实施正确的逻辑。提前致谢 :)
另外,如果我需要在原始查询中添加另外几列,请指导我。我再次添加了我的原始 SQL 查询,添加了另一列。
Select ID,LISTAGG(CATEGORY_CD, ',') WITHIN GROUP(ORDER BY CAST(P_NO as INT)) AS CATEGORY_CD,
LISTAGG(CATEGORY_DTL, ',') WITHIN GROUP(ORDER BY CAST(P_NO as INT)) AS CATEGORY_DTL
FROM table1
WHERE DATE = '2022-02-02'
AND CATEGORY_FLAG = '0'
AND CAT_SRC_CD NOT IN ('0','1','2','3')
group by ID