我是SQL的新手,我尝试了几种方法来解决似乎是一个简单问题但根本没有成功的问题。
我有两个表:
客户
ID_ | EMAIL
----+-------------------
01 | JOHN@GMAIL.COM
02 | MARY@HOTMAIL.COM
03 | PAUL@LIVE.COM
订单
ID | ID_ORDER | SKU
----+---------------+------
01 | 0101 | 123
01 | 0101 | 456
01 | 0102 | 789
02 | 0201 | 124
02 | 0201 | 562
03 | 0301 | 896
我需要列出获得多个订单的客户,以获取ID,EMAIL和ID_ORDER列。我的最后尝试是:
SELECT CUSTOMERS.ID_, CUSTOMERS.EMAIL, ORDERS.ID_ORDER
FROM CUSTOMERS
JOIN ORDERS ON CUSTOMERS.ID_ = ORDERS.ID
GROUP BY CUSTOMERS.ID_
HAVING COUNT(CUSTOMERS.ID_) > 1
答案 0 :(得分:0)
如果要将订单ID排在一起,则需要对其进行汇总。在Oracle中,您可以使用VM Contributor
:
listagg()
要在不同的行上获取这些信息,请使用窗口函数:
SELECT c.ID_, c.EMAIL, LISTAGG(o.ID_ORDER, ';') WITHIN GROUP (ORDER BY o.ID_ORDER) as id_orders
FROM CUSTOMERS c JOIN
ORDERS o
ON c.ID_ = o.ID
GROUP BY c.ID_, c.EMAIL
HAVING COUNT(*) > 1;
答案 1 :(得分:0)
首先通过分组来获得多于1个订单的客户,然后加入表格:
SELECT DISTINCT
c.ID_, c.EMAIL, o.ID_ORDER
FROM (
SELECT ID
FROM ORDERS
GROUP BY ID
HAVING COUNT(DISTINCT ID_ORDER) > 1
) g
INNER JOIN CUSTOMERS c ON c.ID_ = g.ID
INNER JOIN ORDERS o ON o.ID = c.ID_
或:
SELECT DISTINCT
c.ID_, c.EMAIL, o.ID_ORDER
FROM CUSTOMERS c INNER JOIN ORDERS o
ON o.ID = c.ID_
WHERE c.ID_ IN (
SELECT ID
FROM ORDERS
GROUP BY ID
HAVING COUNT(DISTINCT ID_ORDER) > 1
)