如何通过mysql进行嵌套选择与组

时间:2018-09-11 15:44:56

标签: mysql sql

请给我这张桌子

id| statut | datecreation
1 | appel  |10-09-2018
2 | message|10-09-2018
3 | message|11-09-2018
4 | message|11-09-2018
5 | appel  |12-09-2018

我想要这样

date        |Nbappel |Nbmessage
10-09-2018  |   1    |1
11-09-2018  |   0    |2
12-09-2018  |   1    |0

2 个答案:

答案 0 :(得分:2)

您可以尝试:

SELECT datecreation as date, 
       SUM(case when statut='appel' then 1 else 0 end) as Nbappel,
       SUM(case when statut='message' then 1 else 0 end) as Nbmessage  
  FROM t
 GROUP BY datecreation
 ORDER BY datecreation;

SQL Fiddle Demo

答案 1 :(得分:1)

您可以进行条件聚合:

select datecreation, 
       sum( statut = 'appel' ) as Nbappel, 
       sum( statut = 'message' ) as Nbmessage
from table t
group by datecreation;