0

我正在用 LISTAGG 编写 ORACLE 选择语句。它可以工作,但是当我验证数据时,我看到了像 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
4

2 回答 2

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;
于 2016-07-13T16:13:18.833 回答
0

假设Table2PERSON_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

然后更改Table2T2in LISTAGG()(包括在WITHIN GROUP (ORDER BY ...)子句中!)

于 2016-07-13T23:06:19.403 回答