0

在 SQL Server 中,假设我们有一个SALES_HISTORY如下表。

CustomerNo  PurchaseDate    ProductId
    1         20120411         12
    1         20120330         13
    2         20120312         14
    3         20120222         16
    3         20120109         16

...以及每个客户每次购买的许多记录...

如何编写适当的查询以进行查找:

对于每一位客户,

  • 找到他在 MOST 买的产品,
  • 求该产品占他购买的所有产品的百分比。

结果表必须具有如下列:

CustomerNo, 
MostPurchasedProductId, 
MostPurchasedProductPercentage
4

2 回答 2

1

假设 SQL Server 2005+,您可以执行以下操作:

;WITH CTE AS
(
    SELECT *, 
           COUNT(*) OVER(PARTITION BY CustomerNo, ProductId) TotalProduct,
           COUNT(*) OVER(PARTITION BY CustomerNo) Total
    FROM YourTable
), CTE2 AS
(
    SELECT *,
           RN = ROW_NUMBER() OVER(PARTITION BY CustomerNo 
                                  ORDER BY TotalProduct DESC)
    FROM CTE
)
SELECT CustomerNo, 
       ProductId MostPurchasedProductId, 
       CAST(TotalProduct AS NUMERIC(16,2))/Total*100 MostPurchasedProductPercent
FROM CTE2
WHERE RN = 1

当您拥有不止一种产品作为最常购买的产品时,您仍然需要进行交易。这是一个带有演示的 sqlfiddle供您尝试。

于 2013-04-12T15:30:39.060 回答
0

可以做得更漂亮,但它有效:

with cte   as(
select CustomerNo, ProductId, count(1) as c
from SALES_HISTORY
group by CustomerNo, ProductId)

select CustomerNo, ProductId as MostPurchasedProductId, (t.c * 1.0)/(select sum(c) from cte t2 where t.CustomerNo = t2.CustomerNo) as MostPurchasedProductPercentage
from cte t
where c = (select max(c) from cte t2 where t.CustomerNo = t2.CustomerNo)

SQL小提琴

于 2013-04-12T15:28:04.413 回答