mysql获取表时间段的数据,MySQL:选择日期范围之间的所有日期,并获取表数据匹配的日期...

There is a table which has data as such:

-----------------------

| id | date |

-----------------------

| 1 | 2016-07-11 |

| 2 | 2016-07-11 |

| 3 | 2016-07-15 |

| 4 | 2016-07-15 |

| 5 | 2016-07-15 |

| 6 | 2016-07-16 |

| 7 | 2016-07-19 |

| 8 | 2016-07-20 |

-----------------------

I want to get a date range (all dates) and the count of IDs for each date, returning 0 when no records exist.

If run for dates between 2016-07-10 to 2016-07-20, the result should look like this:

--------------------------

| date | count(id) |

--------------------------

| 2016-07-10 | 0 |

| 2016-07-11 | 2 |

| 2016-07-12 | 0 |

| 2016-07-13 | 0 |

| 2016-07-14 | 0 |

| 2016-07-15 | 3 |

| 2016-07-16 | 1 |

| 2016-07-17 | 0 |

| 2016-07-18 | 0 |

| 2016-07-19 | 1 |

| 2016-07-20 | 1 |

--------------------------

I've found solutions for getting a date range but couldn't figure out how to get it to count the IDs that exist for those dates within a table.

Thanks!

解决方案

I figured this out by modifying the query given in the solution for getting all dates.

The following query returns all dates, and counts of the IDs if any records exist:

select d.date, count(v.id) from

(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) date from

(select 0 i 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 i 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 i 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 i 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 i 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) d

left join visitors v on d.date = v.date

where d.date between '2016-06-01' and '2016-06-30'

group by d.date

order by d.date

Courtesy for getting the dates range goes to @mark-bannister and a simple join on the query matching for results, and sorting gets the solution.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值