我有一张如下表格。我想计算前5%客户的金额和接下来的20%以及接下来的25%和接下来的25%,最后剩下的金额。这只是DB表的示例。
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
答案 0 :(得分: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