我正在用LISTAGG编写一个ORACLE select语句。它有效,但是当我验证数据时,我看到了重复数据,如1:1,1:1,2:2,2:2。
我确认数据库确实有重复。该查询用于一对多关系中的两个表。下面是我的查询片段,但我更改了列名等。
如何修改以下查询以返回每个人的唯一值?
由于
SELECT Table1.PERSON_ID,
Table1.FIRST_NAME,
Table1.MIDDLE_NAME,
Table1.LAST_NAME,
LISTAGG(case
when Table2.DESCRIPTION = '1' then '1:1'
when Table2.DESCRIPTION = '2' then '2:2'
when Table2.DESCRIPTION = '3' then '3:3'
when Table2.DESCRIPTION = '4' then '4:4'
when Table2.DESCRIPTION = '5' then '5:5'
when Table2.DESCRIPTION = '6' then '6:6'
when Table2.DESCRIPTION = '7' then '7:7'
when Table2.DESCRIPTION = '8' then '8:8'
when Table2.DESCRIPTION = '9' then '9:9'
else ''
end, ',')
WITHIN GROUP (ORDER BY Table2.DESCRIPTION )
FROM Table1
LEFT JOIN Table2
ON Table2.PERSON_ID = Table1.PERSON_ID
GROUP BY Table1.PERSON_ID,Table1.FIRST_NAME,Table1.MIDDLE_NAME, Table1.LAST_NAME
答案 0 :(得分:2)
在Oracle中,您需要在子查询中执行DISTINCT
:
SELECT PERSON_ID, FIRST_NAME, MIDDLE_NAME, LAST_NAME,
LISTAGG(val, ',') WITHIN GROUP (ORDER BY DESCRIPTION )
FROM (SELECT DISTINCT Table1.PERSON_ID, Table1.FIRST_NAME, Table1.MIDDLE_NAME, Table1.LAST_NAME, Table2.Description
(case when Table2.DESCRIPTION = '1' then '1:1'
when Table2.DESCRIPTION = '2' then '2:2'
when Table2.DESCRIPTION = '3' then '3:3'
when Table2.DESCRIPTION = '4' then '4:4'
when Table2.DESCRIPTION = '5' then '5:5'
when Table2.DESCRIPTION = '6' then '6:6'
when Table2.DESCRIPTION = '7' then '7:7'
when Table2.DESCRIPTION = '8' then '8:8'
when Table2.DESCRIPTION = '9' then '9:9'
else ''
end) as val
FROM Table1 LEFT JOIN
Table2
ON Table2.PERSON_ID = Table1.PERSON_ID
)
GROUP BY PERSON_ID, FIRST_NAME, MIDDLE_NAME, LAST_NAME;
答案 1 :(得分:0)
假设Table2
有PERSON_ID
作为指向Table1
的外键,您需要做的是替换
FROM Table1
LEFT JOIN Table2
ON Table2.PERSON_ID = Table1.PERSON_ID
与
FROM Table1
LEFT JOIN
(SELECT DISTINCT PERSON_ID, DESCRIPTION FROM Table2) T2
ON T2.PERSON_ID = Table1.PERSON_ID
然后在Table2
中将T2
更改为LISTAGG()
(包括在WITHIN GROUP (ORDER BY ...)
子句中!)