2013-02-21 61 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