繁体   English   中英

在 LISTAGG 查询中返回多个相同的行

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM