我有一些表,我猜有一些Query,我想得到一行的总数而不是一列。
我的查询:
SELECT
SUM(CASE WHEN type = '0' THEN duration END) AS 'type0',
SUM(CASE WHEN type = '1' THEN duration END) AS 'type1',
SUM(CASE WHEN type = '2' THEN duration END) AS 'type2'
FROM table1
GROUP BY range
ORDER BY range
我得到了什么:
┌──────────────────┬──────────────────┬──────────────────┐
│ type0 │ type1 │ type2 │
├──────────────────┼──────────────────┼──────────────────┤
│ 59989.3049204680 │ 25232.1543858130 │ 24831.1788671015 │
│ 3306.3676530180 │ 1705.9501506120 │ 2657.4211752480 │
│ 352.0299258450 │ 1692.4885264580 │ 1805.3495437180 │
│ 37.4959716400 │ 1584.6392620720 │ 1343.1338054350 │
│ 8.6286011400 │ 1392.7870618600 │ 1042.1155937090 │
│ 9.4098509860 │ 1269.7669830510 │ 970.8922643280 │
│ 7.6270751800 │ 1163.2768018390 │ 836.8802361650 │
│ 2.9459229000 │ 873.3172769110 │ 464.6357979220 │
│ 3.2543335080 │ 695.5214343770 │ 380.5008553400 │
│ 5.4269405200 │ 3120.0459350020 │ 3603.2397332800 │
└──────────────────┴──────────────────┴──────────────────┘
我想要得到的东西:
┌────────┬────────┬────────┐
│ type0 │ type1 │ type2 │
├────────┼────────┼────────┤
│ 54,51% │ 22,93% │ 22,56% │
│ 43,11% │ 22,24% │ 34,65% │
│ 9,14% │ 43,96% │ 46,89% │
│ 1,26% │ 53,44% │ 45,30% │
│ 0,35% │ 57,00% │ 42,65% │
│ 0,42% │ 56,43% │ 43,15% │
│ 0,38% │ 57,94% │ 41,68% │
│ 0,22% │ 65,13% │ 34,65% │
│ 0,30% │ 64,44% │ 35,26% │
│ 0,08% │ 46,37% │ 53,55% │
└────────┴────────┴────────┘
我知道如何制作每行的百分比:
CAST(100 * SUM(duration) / SUM(SUM(duration)) OVER () AS DECIMAL(5, 2))
作为窗口功能,但我不知道用行做同样的技巧。
答案 0 :(得分:3)
只需在SELECT子句中进行数学运算:
SELECT
SUM(CASE WHEN type = 0 THEN duration END)/SUM(CASE WHEN type in (0,1,2) THEN duration END) as type1_perc,
SUM(CASE WHEN type = 1 THEN duration END)/SUM(CASE WHEN type in (0,1,2) THEN duration END) as type2_perc,
SUM(CASE WHEN type = 2 THEN duration END)/SUM(CASE WHEN type in (0,1,2) THEN duration END) as type3_perc
FROM table1
GROUP BY range
ORDER BY range
答案 1 :(得分:0)
这是一个使用临时表的选项。
SELECT
SUM(CASE WHEN type = '0' THEN duration END) AS 'type0',
SUM(CASE WHEN type = '1' THEN duration END) AS 'type1',
SUM(CASE WHEN type = '2' THEN duration END) AS 'type2'
INTO #TEMP
FROM table1
GROUP BY range
select type0/Sum(type0),type1/Sum(type1),type2/Sum(type2)
from #TEMP