2015-03-31 58 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