0

In SQL Server, suppose we have a SALES_HISTORY table as below.

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

... and many records for each purchase of each customer...

How can I write the appropriate query for finding:

For each customer,

  • find the product he bought at MOST,
  • find the percentage of this product over all products he bought.

The result table must have columns like:

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 に答える