在SQL中为您的每个最佳客户找到最畅销的商品

问题描述 投票:0回答:1

我有3个表:产品(产品ID,产品名称,产品价格),客户(产品ID,地址,电子邮件,名称)和销售(产品ID,客户ID,产品ID)。

我写了一个查询来查找排名前100位的客户(以所花的钱计算:]

SELECT TOP 100 C.name AS customer_name,
SUM(P.prod_price) AS total_spent
FROM customers C
LEFT JOIN Sales S ON C.cust_id=S.cust_id
LEFT JOIN Products P ON S.prod_id=P.prod_id
GROUP BY C.cust_id
ORDER BY total_spent DESC;

现在,我想写一个查询,告诉我这100个客户中每一个的最畅销商品,但我不知道。我试图编写一个嵌套查询,但是它不起作用:

SELECT P.prod_name as best_seller,
C.name AS customer_name
FROM Product P
LEFT JOIN Sales S ON P.prod_id=S.prod_id
LEFT JOIN Customers C on S.cust_id = C.cust_id
GROUP BY C.name, P.prod_name
WHERE C.name IN
    (SELECT C.name AS customer_name
     FROM customers C
     LEFT JOIN Sales S ON C.cust_id=S.cust_id
     LEFT JOIN Products P ON S.prod_id=P.prod_id
     GROUP BY C.cust_id
     ORDER BY total_spent DESC
     LIMIT 100);

我最终将使用sql在10gb的数据集上运行这些查询,但是我已经在SQlite的一个很小的子集上对其进行了测试,因此在我确定它们可以正常工作之前,我不必启动一个实例(因此使用LIMIT 100语法)。在SQLite中,我得到的唯一错误是“在“ WHERE”附近:语法错误”。

sql nested-queries nested-query
1个回答
1
投票
SELECT TOP (100) cp.* FROM (SELECT c.cust_id, c.name, p.prod_id, p.prod_name, SUM(P.prod_price) AS product_spend, ROW_NUMBER() OVER (PARTITION BY c.cust_id ORDER BY COUNT(*) DESC) as seqnum, SUM(SUM(p.prod_price)) OVER (PARTITION BY c.cust_id) as total_spent FROM customers C JOIN Sales S ON C.cust_id = S.cust_id JOIN Products P ON S.prod_id = P.prod_id GROUP BY C.cust_id, p.prod_id, p.prod_name ) cp WHERE seqnum = 1 ORDER BY total_spent DESC;

这将按客户和产品汇总一次。它使用窗口函数获取每个客户的总数,然后在外部查询中进行过滤和排序。

使用COUNT(*)中的ORDER BY获得“购买最多”。使用SUM(p.prod_price)获得“花费最多”的信息。
© www.soinside.com 2019 - 2024. All rights reserved.