2013-04-12 95 views
0

在SQL Server中,假設我們有一個SALES_HISTORY表,如下所示。按複雜查詢SQL Server組

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

...併爲每個購買每個客戶的多條記錄...

我如何寫找到相應的查詢:

對每一個客戶,

  • 找到他在MOST購買的產品,
  • 找到該產品在他購買的所有產品中所佔的百分比。

結果表必須有這樣的列:

CustomerNo, 
MostPurchasedProductId, 
MostPurchasedProductPercentage 
+0

對於'CustomerNo' 1的示例會發生什麼情況?我們應該爲'MostPurchasedProductId'返回'productId' 12或14? – Lamak

+0

@siride不,它不是。討論數據庫服務器時,版本非常重要。例如,在SQL 2k或SQL 7中找不到某些功能(如row_number,partition by)。所以如果你想要一個明確的答案,比你應該有一個明確的問題。 – Marian

回答

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 

當您購買多於一種產品時,您仍然需要處理。 Here is a sqlfiddle附帶演示供您試用。

+0

非常感謝拉瑪克。它幫助了很多。 –

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 Fiddle