MySql-按分组和大小写查询

时间:2018-10-10 12:45:19

标签: mysql

我正在尝试使用case whengroup by进行查询,但无法获得正确的结果。

所以,我有这个查询:

select date, type, DAYNAME(date) as dia, count( date) as total ,
 CASE WHEN type = 1 THEN COUNT(date) ELSE 0 END as admin,
 CASE WHEN type = 2 THEN COUNT(date) ELSE 0 END as dis 
from `user_access` 
where `date` >= DATE(NOW()) - INTERVAL 7 DAY 
group by DAYNAME(date), type
limit 7;

我得到这个结果: enter image description here

它通过dayname column复制记录,并且不将admindis记录放在同一行。

但是我需要的是这个

date       | type | dia     | total | admin | dis |
-----------|------|---------|-------|-------|-----|
2018-10-08 |1     |Monday   | 3     | 3     | 0   |
2018-10-09 |1     |Tuesday  | 6     | 1     | 5   |
2018-10-10 |1     |Wednesday| 3     | 2     | 1   |

我已经尝试将其他列分组,但是不起作用。

如果我从分组依据中删除type并选择,请通过以下查询将其返回给我:

    select date, DAYNAME(date) as dia, count( date) as total ,
    CASE WHEN type = 1 THEN COUNT(date) ELSE 0 END as admin,
    CASE WHEN type = 2 THEN COUNT(date) ELSE 0 END as dis 
from `user_access` 
where `date` >= DATE(NOW()) - INTERVAL 7 DAY 
group by DAYNAME(date)
limit 7;

date       | dia     | total | admin | dis |
-----------|---------|-------|-------|-----|
2018-10-08 |Monday   | 3     | 3     | 0   |
2018-10-09 |Tuesday  | 6     | 6     | 0   |
2018-10-10 |Wednesday| 5     | 3     | 0   |

将所有记录以防万一到管理列...

这使我明白,但我做错了事,也许是case

我该如何解决?

谢谢

1 个答案:

答案 0 :(得分:1)

这是您想要的查询:

select MAX(date), DAYNAME(date) as dia, count( date) as total ,
       COUNT(CASE WHEN type = 1 THEN 1 END) as admin,
       COUNT(CASE WHEN type = 2 THEN 1 END) as dis 
from `user_access` 
where `date` >= DATE(NOW()) - INTERVAL 7 DAY 
group by DAYNAME(date);