希望按年份按年份,类型和顺序计算
这是我的user table
:
id type uname date_created
1 fac a 2015-12-28 17:11:19
2 cs b 2015-12-23 19:09:51
3 cs c 2015-12-23 19:09:21
4 stu d 2015-12-31 18:12:41
5 fac e 2015-11-11 00:00:00
6 fac f 2015-10-07 00:00:00
预期结果:
fac stu cs
1 1 2 // month january
1 0 0 // month octomber
1 0 0 // month november
我尝试的是:
SELECT count(u1.id) as fac, count(u2.id) as stu, count(u3.id) as cs
FROM user u
left join user u1 ON u1.faculty = 'yes' AND YEAR(u1.date_created) = 2015
left join user u2 ON u2.faculty = 'no' AND YEAR(u2.date_created) = 2015
left join user u3 ON u3.faculty = 'club_student' AND YEAR(u3.date_created) = 2015
GROUP BY MONTH(u.date_created) ORDER BY MONTH(u.date_created)
给我错误的结果,如:
fac stu cs
6 6 6
6 6 6
24 24 24
答案 0 :(得分:5)
您需要的是PIVOT
命令,用于将行转置为列。实际上,MySQL不支持这种操作,因此我们需要使用CASE WHEN
手动执行此操作(请参阅SQLFiddle):
select
month(date_created) as month,
count(case when faculty = 'yes' THEN 1 END) as fac,
count(case when faculty = 'no' THEN 1 END) as stu,
count(case when faculty = 'club_student' THEN 1 END) as cs
from user
where 1=1
and date_created >= STR_TO_DATE('01-01-2015','%d-%m-%Y')
and date_created < STR_TO_DATE('01-01-2016','%d-%m-%Y')
group by month(date_created)
order by month(date_created)
实际上,你的连接语法没有意义...你连接三次来计算每个表中的id ...从左连接开始,这些表中的数据只有在有这些表时才会返回连接匹配,如果不匹配则返回null ... COUNT
聚合函数中不计算空值,因此您的连接语法可以简化为INNER
连接语法。但是,当您加入相同的表时,甚至不需要INNER
连接,并且实际上并未将FROM
表中的任何列与JOIN
表关联起来。
这样,您定义的过滤器可以缩减为WHERE
过滤器和CASE WHEN
过滤器。
答案 1 :(得分:1)
尝试count(distinct)
:
SELECT count(distinct u1.id) as fac, count(distinct u2.id) as stu,
count(distinct u3.id) as cs
FROM user u left join
user u1
ON u1.faculty = 'yes' AND YEAR(u1.date_created) = 2015 left join
user u2
ON u2.faculty = 'no' AND YEAR(u2.date_created) = 2015 left join
user u3
ON u3.faculty = 'club_student' AND YEAR(u3.date_created) = 2015
GROUP BY MONTH(u.date_created) ORDER BY MONTH(u.date_created)