我有一个看起来像这样的数据集:
Category Date
-------- ----
Backlog 7/18/18
Backlog 7/18/18
Testing 7/18/18
Done 7/18/18
Backlog 7/19/18
Develop 7/19/18
Backlog 7/20/18
Done 7/20/18
Done 7/20/18
我想通过计数/组织来转变:
Backlog Testing Develop Done Date
------- ------- ------- ---- ----
2 1 0 1 7/18/18
2 0 1 0 7/19/18
1 0 0 2 7/20/18
但是,原始数据集每天仍在更新并带有新日期。第二天,将使用Backlog / Develop / Testing / Done标签(日期为7/21/18)将几行添加到表中。如何在sql中创建此转换,同时又考虑到数据集每天都会更新的事实?
答案 0 :(得分:2)
您需要条件聚合:
select sum(Category = 'Backlog') as Backlog,
sum(Category = 'Testing') as Testing,
sum(Category = 'Develop') as Develop,
sum(Category = 'Done') as Done,
date
from table t
group by date;
答案 1 :(得分:0)
select *
from
(
select Category,count(Category) as Total,Date
from yourTableName group by Date,Category
) src
pivot
(
sum(total)
for Category in ([Backlog],[DONE],[Testing])
) piv;
输出将是这样的:
Date1 Backlog DONE Testing
2018-07-18 2 1 1
2018-07-19 2 NULL NULL
2018-07-20 NULL 2 NULL