我有一个SQL Server表Table_1
,其中包含name, subname, value
列
对于每个子名,我可以通过查询获得值的平均值:
select subname, AVG(value) as avg from Table_1 group by subname;
我也可以得到每个名字的值总和:
select name, sum(value) as sum from Table_1 group by name;
我需要每个avg
的{{1}}行的百分比,我无法弄清楚这一点。
编辑:例如。百分比是 - 平均值val1是a1
中总平均值的x% name
看起来像:
select * from Table_1
答案 0 :(得分:1)
WITH data (name, subname, value) AS (
SELECT 'a1', 'val1 ', 20 UNION ALL
SELECT 'a1', 'val2 ', 20 UNION ALL
SELECT 'a1', 'val3 ', 10 UNION ALL
SELECT 'a1', 'val1 ', 40 UNION ALL
SELECT 'a1', 'val2 ', 30 UNION ALL
SELECT 'a2', '2val3', 90 UNION ALL
SELECT 'a2', '2val1', 80 UNION ALL
SELECT 'a2', '2val2', 30 UNION ALL
SELECT 'a2', '2val3', 90 UNION ALL
SELECT 'a2', '2val1', 80 UNION ALL
SELECT 'a2', '2val1', 630
)
SELECT
name,
subname,
percentage = AVG(value) * 100 / SUM(AVG(value)) OVER (PARTITION BY name)
FROM data
GROUP BY
name,
subname
;
输出:
name subname percentage
---- ------- -----------
a1 val1 46
a1 val2 38
a1 val3 15
a2 2val1 68
a2 2val2 7
a2 2val3 23
有用的阅读: