2

我有一些表格,我猜想有一些查询,我想获得行而不是列的总数的百分比。

我的查询:

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))

作为窗口函数,但我不知道对行执行相同操作的技巧。

4

2 回答 2

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
于 2017-12-15T15:36:09.690 回答
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
于 2017-12-15T15:36:12.147 回答