2011-05-18 131 views
0

我有一個如下表。我想計算前5%客戶的金額總和,接下來是20%,接下來的25%和接下來的25%,最後剩下的金額總和。這只是數據庫表的示例。幫我執行SQL查詢

5%=1, so the sum is 100 
Next 20%=4, so sum=1800(200+500+300+800) 
Next 25%=5, so sum=2900(600+800+500+400+600) 
Next 25%=5, so sum=2500(300+800+300+800+300) 
Rest=1400 

Cus_ID Amount 
1004 100 
1064 200 
1126 500 
1280 300 
1678 800 
1719 600 
1862 800 
2109 500 
2892 400 
2957 600 
3097 300 
3205 800 
3399 300 
3460 800 
4169 300 
4380 800 
4689 100 
4886 200 
4906 300 

Result 
5% 20% 25% next 25% Rest 
100 1800 2900 2500 1400 
+1

「第一」 所訂購客戶ID?這是什麼RDBMS? – 2011-05-18 11:56:23

回答

2
WITH T(Cus_ID,Amount) AS 
(
SELECT 1004, 100 UNION ALL 
SELECT 1064, 200 UNION ALL 
SELECT 1126, 500 UNION ALL 
SELECT 1280, 300 UNION ALL 
SELECT 1678, 800 UNION ALL 
SELECT 1719, 600 UNION ALL 
SELECT 1862, 800 UNION ALL 
SELECT 2109, 500 UNION ALL 
SELECT 2892, 400 UNION ALL 
SELECT 2957, 600 UNION ALL 
SELECT 3097, 300 UNION ALL 
SELECT 3205, 800 UNION ALL 
SELECT 3399, 300 UNION ALL 
SELECT 3460, 800 UNION ALL 
SELECT 4169, 300 UNION ALL 
SELECT 4380, 800 UNION ALL 
SELECT 4689, 100 UNION ALL 
SELECT 4886, 200 UNION ALL 
SELECT 4906, 300 
), T2 AS 
(
SELECT *, 
     ROW_NUMBER() OVER (ORDER BY Cus_ID) AS RN, 
     ROW_NUMBER() OVER (ORDER BY Cus_ID)/ CAST(COUNT(*) OVER() AS FLOAT) AS Pct 
FROM T 
), T3(Amount, Grp) AS 
(
SELECT a.Amount, CASE WHEN ISNULL(b.Pct,0) < 0.05 THEN 1 
         WHEN   b.Pct < 0.25 THEN 2 
         WHEN   b.Pct < 0.50 THEN 3 
         WHEN   b.Pct < 0.75 THEN 4 
         ELSE 5 
        END 
FROM T2 a LEFT JOIN T2 b ON b.RN=a.RN-1 
) 
SELECT SUM(Amount) AS Amount, Grp 
FROM T3 
GROUP BY Grp 
+0

我認爲如果你使用了進一步的CTE來避免在'GROUP BY'子句中重複'CASE'表達式,它會看起來更整齊。 – onedaywhen 2011-05-18 13:04:05

+1

@oneday - 是的。同意。 – 2011-05-18 13:14:44