我正在尝试构建一个查询,该查询将向我显示购买所有商品的客户列表。
我想也许 unique 和 EXISTS 选项或者 count() 可能是一个解决方案,但我不确定如何将这一切放在一起。任何帮助将不胜感激。
下面是我的示例数据和预期输出。
CREATE TABLE customers (CUSTOMER_ID, FIRST_NAME, LAST_NAME) AS
SELECT 1, 'Abby', 'Katz' FROM DUAL UNION ALL
SELECT 2, 'Lisa', 'Jones' FROM DUAL UNION ALL
SELECT 3, 'Joanne','Dalton' FROM DUAL;
CREATE TABLE items (PRODUCT_ID, PRODUCT_NAME) AS
SELECT 100, 'Black Shoes' FROM DUAL UNION ALL
SELECT 101, 'Brown Shoes' FROM DUAL UNION ALL
SELECT 102, 'White Shoes' FROM DUAL;
CREATE TABLE purchases (CUSTOMER_ID, PRODUCT_ID, QUANTITY, PURCHASE_DATE) AS
SELECT 1, 100, 1, TIMESTAMP'2024-05-11 09:54:48' FROM DUAL UNION ALL
SELECT 1, 101, 1, TIMESTAMP'2024-05-11 19:54:48' FROM DUAL UNION ALL
SELECT 1, 102, 1, TIMESTAMP'2024-06-09 14:54:48' FROM DUAL UNION ALL
SELECT 3, 100, 1, TIMESTAMP'2024-06-09 11:34:44' FROM DUAL UNION ALL
SELECT 3,102,1, TIMESTAMP '2024-05-10 19:04:18' FROM DUAL;
CUSTOMER_ID FIRST_NAME LAST_NAME DISTINCT_ITEM_CNT
1 Abby Katz 3
您可以使用
PARTITION
ed OUTER JOIN
来生成计数:
SELECT c.*,
p.distinct_item_cnt
FROM customers c
INNER JOIN (
SELECT customer_id,
COUNT(DISTINCT p.product_id) AS distinct_item_cnt
FROM items i
LEFT OUTER JOIN purchases p
PARTITION BY (p.customer_id)
ON (p.product_id = i.product_id)
GROUP BY p.customer_id
HAVING COUNT(DISTINCT p.product_id) = COUNT(i.product_id)
) p
ON p.customer_id = c.customer_id
对于样本数据,输出:
CUSTOMER_ID | FIRST_NAME | LAST_NAME | DISTINCT_ITEM_CNT |
---|---|---|---|
1 | 艾比 | 卡兹 | 3 |