2013-02-21 48 views
0

我試圖做這個基於星期的總和,但是當我使用下面的代碼時,我顯然必須在我的組中放置一週,這意味着輸出每週沒有一個代碼,它具有衆多。有沒有辦法通過在羣裏不使用一週,所以它看起來像避免使用組中的字段

cde channel 201305 201306 201307 
rr1  2  0   0.6  1 

哪裏像現在它看起來像:

cde channel 201305 201306 201307 
rr1  2  0  null  null 
rr1  2  null 0.6  null 
rr1  2  null null  1 

這是我的代碼

select cde, 
case when week = '201305' then CAST((SUM(fin_acc_sum))AS FLOAT)/nullif(SUM(total),0) end as [201305], 
case when week = '201306' then CAST((SUM(fin_acc_sum))AS FLOAT)/nullif(SUM(total),0) end as [201306], 
case when week = '201307' then CAST((SUM(fin_acc_sum))AS FLOAT)/nullif(SUM(total),0) end as [201307], 
channel 
into #base2 
from #acc_ref 
group by cde,channel,week 
order by channel,cde,week 

回答

1

只需添加MAX圍繞每個CASE表達式並從GROUP BY刪除一週

... 
MAX 
(case when week = '201305' then CAST((SUM(fin_acc_sum))AS FLOAT)/nullif(SUM(total),0) end 
) as [201305], 
... 
group by cde,channel 
order by cde,channel 

您正在有效地將行旋轉爲列,因此week在GROUP BY中沒有任何含義

+0

謝謝。我知道得到消息'不能對包含聚集或子查詢的表達式執行聚合函數。' – user1296762 2013-02-21 10:24:05

+0

@ user1296762:將SUM移到CAST外部 – gbn 2013-02-21 15:08:01