2015-03-31 36 views
1

我的问题是,如果我运行此查询:SQL Server创建不需要的行

select 
    l.SiteID, 
    coalesce(sum(case when a.[TypeKey] = 1 then a.Calc else 0 end)/
nullif(case when TypeKey = 1 then count(l.LocationType) else 0 end, 0), 0) as 'My Type 1 avg', 
    coalesce(sum(case when a.[TypeKey] = 2 then a.Calc else 0 end)/
nullif(case when TypeKey = 2 then count(l.LocationType) else 0 end, 0), 0) as 'My Type 2 avg' 
from 
    @NumberOfPeople a 
inner join 
    Dim.Locations l on a.LocationType = l.LocationType 
group by 
    SiteID, TypeKey 

只要找到第二类型的记录,它创造的,而不是将数到两个新的一行我创建的类型平均列。

什么其返回的是:

|SiteID|My Type 1 avg|My Type 2 avg| 
|1  |1.0   |0   | 
|2  |1.5   |0   | 
|3  |2.5   |0   | 
|1  |0.0   |   1.5| 

我希望看到这项查询的结果:

|SiteID|My Type 1 avg|My Type 2 avg| 
|1  |1.0   |   1.5| 
|2  |1.5   |0   | 
|3  |2.5   |0   | 

我想这个问题是在集团通过TypeKey是什么原因造成这种现象?然而,我不能只是删除它欠规则 - 因为它当时抱怨说,它不是由该组的一部分:

TypeKey is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. 

有什么建议?

回答

1

尝试,因为它不是在聚合函数或GROUP BY子句中包含这样的

;WITH grouptable(
select l.SiteID, 
coalesce(sum(case when a.[TypeKey] = 1 then a.Calc else 0 end)/
nullif(case when TypeKey = 1 then count(l.LocationType) else 0 end, 0), 0) as 'My Type 1 avg', 

coalesce(sum(case when a.[TypeKey] = 2 then a.Calc else 0 end)/
nullif(case when TypeKey = 2 then count(l.LocationType) else 0 end, 0), 0) as 'My Type 2 avg' 
from 
@NumberOfPeople a 
inner join Dim.Locations l 
on a.LocationType = l.LocationType 
group by 
SiteID, 
TypeKey 
) 
SELECT SiteID,SUM([My Type 1 avg]) [My Type 1 avg],SUM([My Type 2 avg]) [My Type 2 avg] 
FROM grouptable 
GROUP BY SiteID 
+0

列“grouptable.My 1型平均”在选择列表中无效。 – 2015-03-31 04:30:47

+0

@AlinaVinnichek请尝试更新的查询 – ughai 2015-03-31 04:33:58

+0

啊真棒,欢呼声,现在的作品! – 2015-03-31 04:34:35