mysql:按日期之间的行数

时间:2018-06-27 13:05:54

标签: mysql

enter image description here

在显示的屏幕截图中,显示日期计数失败/丢失 '2018-06-23',2018-06-25,2018-06-26,2018-06-27,您能帮助我编写正确的查询,以便我获得丢失日期的计数。我正在尝试获取特定日期(created_date)的总行数。

SELECT count(book_id) as count,created_date as cdate
FROM `bookdetails`
WHERE  (created_date >= '2018-06-21' AND created_date <='2018-06-27')
GROUP by DATE(created_date)
ORDER BY MIN(created_date)

预期输出:

count   |     cdate
----------------------
98           2018-06-21
39           2018-06-22
0            2018-06-23  //because no data
39           2018-06-24
XX           2018-06-25
XX           2018-06-26
XX           2018-06-27

表:bookdetails结构 enter image description here

2 个答案:

答案 0 :(得分:0)

日期生成和联接需要显示不存在的日期

 select count(book_id) as count,date(C_date) as cdate from

        (
        select * from 
        (select adddate('1970-01-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) C_date from
         (select 0 t0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
         (select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
         (select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
         (select 0 t3 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
         (select 0 t4 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
        where C_date between '2018-01-01' and '2018-12-31'
        ) All_date

        left join bookdetails
        on date(created_date)=All_date.C_date

        where ( date(All_date.C_date) >= '2018-06-21' AND date(All_date.C_date) <='2018-06-27')

        group by date(C_date)
        order by  date(C_date) asc

答案 1 :(得分:-1)

为什么不简单地使用BETWEEN而不是=> and <=

用法:

SELECT * FROM bookdetails 
 WHERE created_date BETWEEN lowerdate AND upperdate

向我们展示您的后端。我们将为您提供更好的帮助。 预期的结果是什么?