我有一个这样的表:
date | page
----- |-----
2018-01-01 | good
2018-01-01 | good
2018-01-01 | good
2018-01-01 | bad
2018-01-02 | good
如何按日期按页面列中的值进行组织:
date | good | bad
----- |------|----
2018-01-01 | 3 | 1
2018-01-02 | 1 | 0
答案 0 :(得分:1)
您需要条件聚合:
select date,
sum(case when page = 'good' then 1 else 0 end) as good,
sum(case when page = 'bad' then 1 else 0 end) as bad
from table t
group by date;
但是,MySQL具有以下简称:
select date,
sum( page = 'good') as good,
sum( page = 'bad' ) as bad
from table t
group by date;
答案 1 :(得分:1)
这可以工作,只需在sum函数中添加一个case:
select date,
sum( case when page = 'good' then 1 else 0 end) as good,
sum( case when page = 'bad' then 1 else 0 end ) as bad
from table t
group by date
答案 2 :(得分:1)
将pivot
表用作
create table #pivot(date date,page varchar(20))
insert into #pivot values
('2018-01-01','good')
,('2018-01-01','good')
,('2018-01-01','good')
,('2018-01-01','bad')
,('2018-01-02','good')
select date,good,bad from(
select date, page from #pivot
) f
pivot
( count(page) for page in (good,bad)
) p
答案 3 :(得分:0)
我不确定您使用的平台是什么,但是如果是在Oracle中,它将执行相同的操作。
select date, sum(decode(page,'good',1,0)) as good, sum(decode(page,'bad',1,0)) as bad
from table t
group by date;