在PIVOT中正确导出平均值

时间:2017-10-13 15:48:53

标签: sql-server pivot

我们的一位经理要求提供一份具有特定格式的报告,其中员工姓名为行,一年中有几个月作为列,每个员工每月平均收入用于填充单元格。日期最终将被@startdate和@enddate变量替换,但为了构建和测试,我已经硬编码了一个日历年。为了完成这个请求,我创建了一个PIVOT查询,但是我的结果集不正确,我很少使用PIVOT查询,所以我不够了解问题,我希望得到一些经常使用它们的人的帮助。 / p>

首先,这是我的查询,它提取没有请求格式的正确结果集:

select d.Name, AVG(gross), s.systemmonth, s.SYSTEMYEAR
from desk d, PAYMENTS s
where d.code = s.DESK
and s.ENTERED between '2017-08-01' and '2017-09-30'
group by name, s.SYSTEMMONTH, s.SYSTEMYEAR
order by name

结果集的几行:

Name    (No column name)    systemmonth SYSTEMYEAR
employee 1  221.5737        8           2017
employee 1  181.2476        9           2017
employee 2  161.62          9           2017
employee 2  321.9311        8           2017
employee 3  249.2245        9           2017
employee 4  328.1208        8           2017
employee 4  198.6748        9           2017
employee 5  76.4833         8           2017
employee 5  96.6896         9           2017

现在我的PIVOT查询:

select name, [1] AS January, [2] AS February, [3] AS March, [4] AS April, 
[5] AS May, [6] AS June, [7] AS July, [8] AS August, [9] AS September, [10] 
AS October, [11] AS November, [12] AS December
from
(select d.Name, s.gross,  s.systemmonth, s.SYSTEMYEAR
from desk d, PAYMENTS s
where d.code = s.DESK
and s.ENTERED between '2017-01-01' and '2017-12-31'
group by name AS Employee, s.gross, s.SYSTEMMONTH, s.SYSTEMYEAR) a
PIVOT
(AVG(gross)
FOR systemmonth IN
([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
) AS pvt
order by name

随附的结果,平均值都是不正确的(但是NULL是正确的)。为了便于阅读和比较,我只花了2个月的时间:

Employee    August    September 
employee 1  279.501   245.478   
employee 2  544.9648  235.9713  
employee 3  NULL      312.5366  
employee 4  403.1505  273.9044  
employee 5  129.8883  239.8701  

有谁能告诉我为什么PIVOT中的平均值计算不正确?谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

尝试从您的数据透视查询中删除此行。你似乎没有理由分组。

group by name AS Employee, s.gross, s.SYSTEMMONTH, s.SYSTEMYEAR

您还可以进行第一次查询并对其进行转移,此时您的枢轴聚合将变为MAXMIN,因为每个员工/月只会在数据集中有1行组合