Mysql组按日期和计数查询

时间:2018-02-01 10:48:08

标签: mysql group-by

我有如下表: - enter image description here

借助MySql查询,我想得到如下结果:

SELECT A.attribute_id, A.product_id
FROM tableA as A
LEFT JOIN (SELECT * FROM tableB) AS B
ON FIND_IN_SET(A.attribute_id, B.`axis`)

4 个答案:

答案 0 :(得分:5)

试试这个:

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

答案 1 :(得分:0)

您可以使用大小写聚合读取的过滤值

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 

答案 2 :(得分:0)

试试这个我们不需要read列中的案例,因为1表示read,所以我们只需sum值。如果我们处理大量数据,它将有助于提高性能:

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

答案 3 :(得分:0)

您必须使用group by按日期对行进行分组,然后您可以使用count计算每个日期组中的总行数(=总列数)。 为了获得已读和未读的数量,您可以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