避免在分组中使用字段

时间:2013-02-21 09:36:44

标签: sql-server-2008

我试图根据周来做这个总和,但是当我使用下面的代码时,我显然必须在我的组中放置一周,这意味着输出每周都没有一个代码,它有很多。有没有办法不在组中使用周,所以看起来像

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 个答案:

答案 0 :(得分:1)

只需在每个CASE表达式周围添加MAX,并从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中没有任何意义

相关问题