简体   繁体   English

MySQL按日期和计数分组

[英]Mysql group by date and count query

I have table as below :- 我有如下表格: 在此处输入图片说明

With help of MySql query, I want result as below: 借助MySql查询,我想要的结果如下:

date        total    read    unread
2018-01-31   8        4        4
2018-02-01   2        2        0

Try this: 尝试这个:

SELECT date, COUNT(*) as total,
SUM(CASE WHEN read = 1 THEN 1 ELSE 0) as read
SUM(CASE WHEN read = 0 THEN 1 ELSE 0) as unread
FROM yourtable
GROUP BY date

you can use case for aggregate the filtered value for read 您可以使用案例汇总过滤后的值以供读取

select date
, count(*), sum(case when  read=1 then 1 else 0 end )  as read
, sum(case when  read=0 then 1 else 0 end )  as unread
from my_table 
group by date 

Try This we don't need case in the read column as 1 means read so we simply sum the value. 尝试此操作在read列中不需要大小写,因为1表示已read因此我们只求sum即可。 It will help in the performance if we are dealing with the huge data: 如果我们处理大量数据,它将对性能有所帮助:

SELECT date, 
    COUNT(*) as total,
    SUM(read) as read --Case not needed here
    SUM(CASE WHEN read = 0 THEN 1 ELSE 0) as unread
FROM yourtable
GROUP BY date

You have to group rows by date using group by , then you can use count to count the total number of rows within each date group (= total column). 您必须使用group by by将日期group bygroup by ,然后可以使用count来计数每个日期组内的总行数(=总列)。 In order to obtain the number of read and unread, you can sum read and unread value 为了获得已读和未读的数量,可以将已读和未读的值sum

        SELECT date
             , COUNT(*) AS total
             , SUM(READ) AS READ
             , SUM(CASE WHEN READ = 0 THEN 1 ELSE 0 END) AS unread
        FROM mytable
        GROUP BY date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM