SQL的平均百分比

时间:2012-02-23 05:35:58

标签: sql sql-server-2008 average

我有一个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

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

有用的阅读: