从oracle中的listagg中删除重复值

时间:2016-10-24 10:18:53

标签: oracle replace listagg

我使用listagg连续书和列出书籍以及补充书名。

SELECT DISTINCT SUBSTR(LISTAGG(',-'||B1.BOOK_NO||','||B1.BOOK_NAME||','||A.AUTHOR_NAME||',-'||B2.BOOK_NO||','||B2.BOOK_NAME)   WITHIN GROUP (ORDER BY B2.BOOK_NO),2) 
FROM BOOK_LIST B1
INNER JOIN AUTHORS A ON A.AUTHOR_NO=B1.AUTHOR_NO
INNER JOIN SUPPLEMENTARY B2 ON B2.BOOK_NO = B1.BOOK_SUP_NO
WHERE B1.SEQ = 123;

但是由于补充书籍的数量越来越多,我反复得到主要的书名。

有没有办法删除重复的主要图书名称和编号。

我的输出是这样的

-99,Anders Carlson ,-109,John Stuart,-99,Anders Carlson ,-47,James Anderson

这里重复值99我只想要一个99.

期望的输出:

-99,Anders Carlson ,-109,John Stuart,-47,James Anderson

数据库数据:

Book_list:

NO | MAIN_BOOK_NO | MAIN_BOOK_NAME | BOOK_SUP_NO | AUTHOR_NO
1  |    12        |    xyz         |   5         |   2
2  |    22        |    abc         |   7         |   4

作者:

NO | AUTHOR_NO | AUTHOR_NAME
 1 |  2        | Alex
 2 |  3        | Leonard
 3 |  4        | Benjamin

补充:

NO | BOOK_NO | BOOK_NAME 
1  |   5     |   ABC
2  |   5     |   XYZ
3  |   7     |   LMN
4  |   7     |   DEF
5  |   7     |   NEW

输出应该像

         NAME
12,xyz,Alex,-5,ABC,-5,XYZ
22,abc,Benjamin,-7,LMN,-7,DEF,-7,NEW

类似于表中的整个数据

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要将补充书籍列表附加到主要书籍中,以便您真正了解以下内容:

SELECT B1.MAIN_BOOK_NO||','||B1.MAIN_BOOK_NAME||',-'||
         LISTAGG(B2.BOOK_NO||','||B2.BOOK_NAME, ',-') WITHIN GROUP (ORDER BY B2.BOOK_NO) 
FROM   BOOK_LIST B1
       INNER JOIN AUTHORS A ON A.AUTHOR_NO=B1.AUTHOR_NO
       INNER JOIN SUPPLEMENTARY B2 ON B2.BOOK_NO = B1.BOOK_SUP_NO
WHERE  B1.SEQ = 123
GROUP BY B1.MAIN_BOOK_NO, B1.MAIN_BOOK_NAME;

答案 1 :(得分:0)

看看是否有效

select T1.MAIN_BOOK_NO, T11.MAIN_BOOK_NAME, LISTAGG(',-'||',-'||T1.BOOK_NO||','||T1.BOOK_NAME) WITHIN GROUP (order by T1.BOOK_NO)
from
(
SELECT B1.MAIN_BOOK_NO, B1.MAIN_BOOK_NAME, B2.BOOK_NO, B2.BOOK_NAME
FROM BOOK_LIST B1
INNER JOIN AUTHORS A ON A.AUTHOR_NO=B1.AUTHOR_NO
INNER JOIN SUPPLEMENTARY B2 ON B2.BOOK_NO = B1.BOOK_SUP_NO
WHERE B1.SEQ = 123
group by B1.MAIN_BOOK_NO, B1.MAIN_BOOK_NAME, B2.BOOK_NO, B2.BOOK_NAME
order by B2.BOOK_NO
) T1 
group by T1.MAIN_BOOK_NO, T1.MAIN_BOOK_NAME;