业务背景 :有一张公众号粉丝关注数总表,按照每天汇总关注总数,解读如下:截止到 2022-01-01 公众号关注总数为: 45087
设计思路:
执行结果:
该实现方式,由于当前所在月还未到最后一天,存在无法获取当前月数据情况。经过考虑,使用 max 取每一个月中最大的一天,最终优化sql如下:
1、这里使用inner join 而非where 子查询,涉及到效率执行问题。
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条)