以下表达式可获取下个月的第一天日期:
DATE_FORMAT(ADDDATE(CURDATE(),INTERVAL '1' MONTH),'%Y-%m-01')
这个日期再减去1天就是月底日期。
下面举例获取今天(2017-01-24)到月底的天数:
select DATEDIFF(
DATE_FORMAT(ADDDATE(CURDATE(),INTERVAL '1' MONTH),'%Y-%m-01'),CURDATE())-1
SELECT ADDDATE(y.first, x.d - 1) as d,x.d as bFROM
(
SELECT @xi:=@xi+1 as d from
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc1,
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7) xc2,
(SELECT 1 ) xc3,
(SELECT @xi:=0) xc0
) X,
(
SELECT '2018-11-01' - INTERVAL DAY('2018-11-01') - 1 DAY AS first,
DAY(LAST_DAY('2018-11-01')) AS last) Y
WHERE x.d <= y.last
或者
SELECT ADDDATE(y.first, x.d - 1) as dFROM
(
SELECT 1 AS d UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9 UNION ALL
SELECT 10 UNION ALL
SELECT 11 UNION ALL
SELECT 12 UNION ALL
SELECT 13 UNION ALL
SELECT 14 UNION ALL
SELECT 15 UNION ALL
SELECT 16 UNION ALL
SELECT 17 UNION ALL
SELECT 18 UNION ALL
SELECT 19 UNION ALL
SELECT 20 UNION ALL
SELECT 21 UNION ALL
SELECT 22 UNION ALL
SELECT 23 UNION ALL
SELECT 24 UNION ALL
SELECT 25 UNION ALL
SELECT 26 UNION ALL
SELECT 27 UNION ALL
SELECT 28 UNION ALL
SELECT 29 UNION ALL
SELECT 30 UNION ALL
SELECT 31
) x,
(
SELECT '2018-11-01' - INTERVAL DAY('2018-11-01') - 1 DAY AS first,
DAY(LAST_DAY('2018-11-01')) AS last) y
WHERE x.d <= y.last
然后你应该知道了吧
SELECTd.d,
count(t.id)
FROM
(
-- 这里贴前面两段代码中的任意一段
) d
LEFT JOIN
table t ON t.day = d.d -- 这个table是你要查的数据表
GROUP BY
d.d
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)