select & 连接表并合并部分重复的结果

select & Join tables and combine partially duplicated results

我有 5 张桌子。

我正在尝试 select 并加入,这样我就可以为每个客户安排一行 returned。这是我目前拥有的:

SELECT CUSTOMER.CUSTFNAME || ' ' || CUSTOMER.CUSTLNAME AS "CUSTOMER",
ORDERITEM.ITEMDESC AS "ITEMS PURCHASED", 
RETURNITEM.ITEMDESCS "RETURNS",
STATES.STATENAME
FROM CUSTOMER 
INNER JOIN ORDER ON CUSTOMER.CUSTID = ORDER.CUSTID
INNER JOIN ORDERITEM ON ORDER.OITEMID = ORDERITEM.OITEMID
INNER JOIN RETURN ON CUSTOMER.CUSTID = RETURN.CUSTID
INNER JOIN RETURNITEM ON RETURN.RITEMID = RETURNITEM.RITEMID
INNER JOIN STATES ON CUSTOMER.STATEID = STATES.STATEID;

哪个有效,除了...

我有一个客户有两个订单(两个项目)和两个 returns(两个 return 项目)。而不是看到:

---Customer------ITEMS PURCHASED------------RETURNS

Joe Snuffy       widget 1                   widget 1
joe snuffy       widget 2                   widget 1
joe snuffy       widget 1                   widget 2
joe snuffy       widget 2                   widget 2

我的最终目标是看到:

---Customer------ITEMS PURCHASED------------RETURNS

Joe Snuffy       widget 1, widget 2         widget 1, widget 2

有办法吗?最好是一个不是超级复杂的函数之类的哈哈...

TIA!

很遗憾您使用的是 18c 而不是 19c,您可以在 LISTAGG 上使用新的 DISTINCT 标志。实际上,您只需要将其拆分一下即可:

SELECT CUSTOMER.CUSTFNAME || ' ' || CUSTOMER.CUSTLNAME AS "CUSTOMER",
o.purchased AS "ITEMS PURCHASED", 
r.returned "RETURNS",
STATES.STATENAME
FROM CUSTOMER c
INNER JOIN (SELECT o.custid, 
                   LISTAGG(oi.itemdesc, ', ') WITHIN GROUP (ORDER BY oi.itemdesc) AS PURCHASED
            FROM ORDER o
            INNER JOIN ORDERITEM oi ON o.OITEMID = oi.OITEMID
            GROUP BY o.custid) o ON c.custid = o.custid
INNER JOIN (SELECT r.custid,
                   LISTAGG(ri.itemdesc, ', ') WITHIN GROUP (ORDER BY ri.itemdesc) AS RETURNED
            FROM RETURN r
            INNER JOIN RETURNITEM ri ON r.RITEMID = ri.RITEMID
            GROUP BY r.custid) r ON c.custid = r.custid
INNER JOIN STATES ON CUSTOMER.STATEID = STATES.STATEID;

在这段代码中,我只是 LISTAGG 单独的列表,然后将它们连接在一起。