Tsql sql server会创建不需要的行

Tsql sql server会创建不需要的行,tsql,sql-server-2012,Tsql,Sql Server 2012,我遇到的问题是,如果我运行此查询: 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 th

我遇到的问题是,如果我运行此查询:

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          |          1.5| 
|2     |1.5          |0            | 
|3     |2.5          |0            |
每当它找到第二种类型的记录时,就会创建一个新行,而不是将数字放入我创建的两个类型平均列中

它的回报是:

|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|
我希望从此查询中看到的结果:

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          |          1.5| 
|2     |1.5          |0            | 
|3     |2.5          |0            |
我想问题在于分组时的类型键是什么导致了这种行为?然而,我不能仅仅因为规则而将其删除,因为它随后抱怨说它不是该组的一部分,因为:

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

有什么建议吗?

试试这样的建议

;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

列“grouptable.My Type 1 avg”在选择列表中无效,因为它未包含在聚合函数或GROUP BY子句中。