mysql 上个月,MySQL:选择上个月和之前一个月

I am trying to write a reporting page that will

(PART A) Select records from the current calendar month (so if accessed on June 10, it will show records from June 1 to June 10)

(PART B) Then another section for the previous calendar month (so May 1 to May 31).

I've played around with the example in this discussion MySQL Query to calculate the Previous Month

But am a little bit confused.

Will

SELECT Count(*)

FROM `table`

WHERE table.timestamp BETWEEN date_format(NOW() - INTERVAL 1 MONTH, '%Y-%m-01') AND last_day(NOW() - INTERVAL 1 MONTH)

satisfy (PART A) or (PART B)?

It seems like it is (PART A) but I am pretty confused.

Can you help me build both queries? This SQL datetime stuff really messes with my head.

解决方案

If you subtract the current day of the month from the date and add 1, you have the beginning of the current month. You can use this logic:

where time between date_sub(curdate(), interval day(curdate()) - 1 day) and

date_sub(date_add(date_sub(curdate(), interval day(curdate()) - 1 day), interval 1 month), interval -1 day)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值