0

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

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
4

1 回答 1

1

只需在每个 CASE 表达式周围添加 MAX 并从 GROUP BY 中删除 week

...
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 中没有任何意义

于 2013-02-21T10:17:28.980 回答