运行 分组记录唯一值的聚合函数

Run aggregate functions on grouped records unique values

这应该是一个相当简单的任务。我可以用 cursor 完成它,但我真的想像常规 query 那样完成它。 Table摘要如下:CustIdProductIdOrderIdUnitPriceLineTotal。我需要为每个 CustIdProductId 获取所有 LineTotalSUM() 和所有唯一 OrderIdCOUNT(),其中 ProductId 是在至少 2 个不同的 OrderId 上相同。我的查询如下所示,但经过验证我意识到 OrderId 的唯一性受到损害,因此 aggregate 函数 return 不正确的结果。请指教。

SELECT h.CustId
    , h.ProductId
    , h.COUNT(DISTINCT h.OrderId)
    , h.SUM(h.LineTotal)
FROM History h
GROUP BY h.CustId
    , h.ProductId
HAVING COUNT(h.OrderId) > 1

where ProductId is the same on at least 2 different OrderId.

您需要使用 IN(sub-query)(或者 EXISTS() 也可以)构造而不是 HAVING 来强制执行此要求。这是因为您按 ProductIdCustId 进行分组,但此要求仅针对 ProductId,不应受到 CustId.

的影响

在伪代码中

WHERE ProductId IN (SELECT ProductIds that have at least 2 different OrderIds)

你想要HAVING COUNT(DISTINCT h.OrderId) > 2而不是HAVING COUNT(h.OrderId) > 1,这不就是2个不同的OrderId的意思吗?如果不使用 > 1 但保留 DISTINCT:

SELECT h.CustId
    , h.ProductId
    , h.COUNT(DISTINCT h.OrderId)
    , h.SUM(h.LineTotal)
FROM History h
GROUP BY h.CustId
    , h.ProductId
HAVING COUNT(DISTINCT h.OrderId) > 2