sql server创建不需要的行

时间:2015-03-31 04:19:47

标签: 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 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            |

我猜问题是在Group By TypeKey中导致这种行为的原因是什么?然而,我不能仅仅因为规则而删除它 - 因为它然后抱怨它不属于该组:

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

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

尝试这样的事情

;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