SQL计算已订购同一产品至少7次的客户

时间:2019-11-11 05:23:41

标签: mysql sql sql-server database relational-database

我有下表

–价格(产品ID ,来自价格)

–产品(产品ID ,名称,数量)

– PO(产品ID 订单ID ,金额)

–订单( orderID ,日期,地址,状态,trackingNumber,custID,shipID)

–送货( shipID ,公司,时间,价格)

–客户(客户ID ,姓名)

–地址( addrID ,客户ID,地址)

我想找到至少购买过7次相同商品的客户名称,如果他们一次订购两次相同商品,我想将其视为一个。这是我的代码:

SELECT C.name, COUNT(DISTINCT p.prodId) as prod_count
FROM Product P
INNER JOIN PO
ON PO.prodId = P.prodId
INNER JOIN "Order" O
ON O.orderId = PO.orderId
INNER JOIN Customer C
ON C.custId = O.custId
GROUP BY c.name
HAVING COUNT(DISTINCT p.prodId) > 6;

但是,这返回的是每个客户订购的独特产品的数量,这并不是我想要的。

2 个答案:

答案 0 :(得分:1)

我们可以在此处尝试使用两个级别的聚合。聚合的第一级是按客户,订单和产品进行的,如果给定的客户在同一订单中多次订购同一产品,则删除重复项。下一级别的汇总仅按客户和产品进行,并且仅保留至少拥有一种产品的客户,这些产品在不同订单中购买了7次或以上。最后,我们做一个独特的选择来保留每个唯一匹配的客户名称。

WITH cte1 AS (
    SELECT c.name, o.orderId, p.prodId
    FROM Customer c
    INNER JOIN "Order" o ON o.custId = c.custId
    INNER JOIN PO po ON po.orderId = o.orderId
    INNER JOIN Product p ON p.prodId = po.prodId
    GROUP BY c.name, o.orderId, p.prodId
),
cte2 AS (
    SELECT name, prodId
    FROM cte1
    GROUP BY name, prodId
    HAVING COUNT(*) >= 7
)

SELECT DISTINCT name
FROM cte2;

答案 1 :(得分:0)

据我所知,没有必要与Product表联接,除非结果中需要Product名称。

;with CTE as(
    SELECT orderId,prodId, COUNT(*) as OrderProd_Count
    FROM dbo.PO
    GROUP BY orderId,prodId
    )
    ,CTE1 as(
    SELECT prodId,count(*) as Prod_Count
    from CTE
    group by prodId
    having count(*)>7
    )
    select c1.productid,ca.Name from CTE1 C1
    inner join CTE C on c1.prodId=c1.prodId
    inner join dbo.Order O on c.orderid=O.orderId
    inner join Customer  C on o.custid=C.custid