[英]Returning multiple identical rows in LISTAGG query
我正在使用 Oracle,並希望將兩個表連接到一個選擇語句中(用於報告),我們需要將一個表中的一些數據連接到一行中 - 我希望使用 LISTAGG .
問題的簡化版:
帳戶表:
初始日期 | 賬號 | 平衡 |
---|---|---|
01/01/1980 | 11111 | 20 |
02/01/1980 | 22222 | 30 |
03/01/1980 | 33333 | 40 |
04/01/1980 | 44444 | 50 |
ACCOUNT_TO_CUST 表:
賬號 | 客戶編號 |
---|---|
11111 | 50 |
22222 | 51 |
22222 | 52 |
33333 | 53 |
44444 | 51 |
44444 | 55 |
44444 | 57 |
我想要得到的是這樣的:
賬號 | 顧客 | 初始日期 | 平衡 |
---|---|---|---|
11111 | 50 | 01/01/1980 | 20 |
22222 | 51,52 | 02/01/1980 | 30 |
33333 | 53 | 03/01/1980 | 40 |
44444 | 51、55、57 | 04/01/1980 | 50 |
但是,我實際看到的是重復的行,這會破壞報告工具:
賬號 | 顧客 | 初始日期 | 平衡 |
---|---|---|---|
11111 | 50 | 01/01/1980 | 20 |
22222 | 51,52 | 02/01/1980 | 30 |
22222 | 51,52 | 02/01/1980 | 30 |
我目前的查詢是
SELECT a.AccountNumber,
LISTAGG(ac.Customers, ',') WITHIN GROUP (ORDER BY a.AccountNumber)
a.InitialDate,
a.balance
FROM accounts a, account_to_cust ac
WHERE accounts.AccountNumber = account_to_cust.AccountNumber
Group By a.AccountNumber, a.InitialDate, a.balance
我試過在初始選擇中放入一個 distinct ,並得到一個連接太長的錯誤,我已經嘗試在 LISTAGG 本身中添加 distinct ,這似乎也不起作用。 如何消除這些重復項?
這對我來說看起來沒問題(第 1 - 16 行中的示例數據;查詢從第 17 行開始):
SQL> with
2 accounts (initialdate, accountnumber, balance) as
3 (select date '1980-01-01', 11111, 20 from dual union all
4 select date '1980-01-02', 22222, 30 from dual union all
5 select date '1980-01-03', 33333, 40 from dual union all
6 select date '1980-01-04', 44444, 50 from dual
7 ),
8 account_to_cust (accountnumber, custno) as
9 (select 11111, 50 from dual union all
10 select 22222, 51 from dual union all
11 select 22222, 52 from dual union all
12 select 33333, 53 from dual union all
13 select 44444, 51 from dual union all
14 select 44444, 55 from dual union all
15 select 44444, 57 from dual
16 )
17 select
18 a.accountnumber,
19 a.initialdate,
20 a.balance,
21 listagg(b.custno, ', ') within group (order by b.custno) customers
22 from accounts a join account_to_cust b on b.accountnumber = a.accountnumber
23 group by a.accountnumber,
24 a.initialdate,
25 a.balance
26 order by a.accountnumber;
ACCOUNTNUMBER INITIALDATE BALANCE CUSTOMERS
------------- --------------- ---------- ---------------
11111 01/01/1980 20 50
22222 02/01/1980 30 51, 52
33333 03/01/1980 40 53
44444 04/01/1980 50 51, 55, 57
SQL>
如您所見,沒有重復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.