SQL来自行总和的每个值的百分比

时间:2017-12-13 13:21:30

标签: sql sql-server percentage

我正在尝试从此查询中获取每个值的百分比。我知道这个问题可能是重复的,但我无法使其成功。

SELECT SUM(distance) AS SUM_DISTANCE FROM table1 GROUP BY type

它给了我这个:

+------------------+
|   SUM_DISTANCE   |
+------------------+
| 60159.7965819000 |
|   289.0123500000 |
| 34660.5349672000 |
+------------------+

我想得到的是:

+-----------------+
| PercentDistance |
+-----------------+
|           63,25 |
|            0,30 |
|           36,44 |
+-----------------+

这是我的尝试:

WITH Total AS
    (SELECT SUM(distance) AS SUM_DISTANCE FROM table GROUP BY type)
select
    (total.SUM_DISTANCE / sum(distance)) * 100 AS PercentDistance
FROM table1, Total
GROUP BY Total.SUM_DISTANCE;

这是我尝试的结果:

+-----------------+
| PercentDistance |
+-----------------+
|        0.001300 |
|        0.159900 |
|        0.277600 |
+-----------------+

2 个答案:

答案 0 :(得分:4)

使用窗口功能:

SELECT CAST(100 * SUM(distance) / SUM(SUM(distance)) OVER () AS DECIMAL(5, 2)) AS percentage
FROM table1
GROUP BY type;

答案 1 :(得分:0)

SELECT
    SUM(distance) / (SELECT SUM(distance) FROM table1) AS SUM_DISTANCE
FROM table1
GROUP BY type