如何将一行替换为多行而不是多行

时间:2015-11-20 01:28:34

标签: sql sql-server conditional-aggregation

我有以下数据:

enter image description here

在SQL Server中如何按weekdate分组,因此每个weekdate只有一行,weekdate 2015-11-14

enter image description here

  

有任何线索吗?

2 个答案:

答案 0 :(得分:4)

使用条件聚合。

select cast(weekdate as date), 
sum(case when permittype = 0 then total else 0 end) as permittype0,
sum(case when permittype = 1 then total else 0 end) as permittype1
from tablename
group by cast(weekdate as date)

答案 1 :(得分:1)

我会使用条件聚合来做到这一点:

select weekdate,
       sum(case when permittype = 0 then total else 0 end) as permitttype0,
       sum(case when permittype = 1 then total else 0 end) as permitttype1
from followingdata t
group by weekdate
order by weekdate;

如果您愿意,也可以使用pivot语法。