select detail_id,DATE_FORMAT(create_date,'%Y-%m-%d') date ,sum(diff_data) from report where detail_id in (3304) and DATE_FORMAT(create_date,'%Y-%m-%d') = '2020-12-18' group by detail_id order by date asc ;
select detail_id,DATE_FORMAT(create_date,'%Y-%m') date ,sum(diff_data) from report where detail_id in (3304) and DATE_FORMAT(create_date,'%Y-%m') = '2020-12' group by detail_id order by date asc ;
select detail_id,CONCAT(YEAR(create_date),'_',quarter(create_date)) date ,sum(diff_data) from report
where detail_id in (3304) and CONCAT(YEAR(create_date),'_',quarter(create_date)) = '2020_4' group by detail_id order by date asc ;
select detail_id,DATE_FORMAT(create_date,'%Y') date ,sum(diff_data) from report where detail_id in (3304) and DATE_FORMAT(create_date,'%Y') = '2020' group by detail_id order by date asc ;
1.建立时间维度表
CREATE TABLE num (i int);-- 创建一个表用来储存0-9的数字
INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);-- 生成0-9的数字,方便以后计算时间
CREATE TABLE if not exists calendar(datelist date); -- 生成一个存储日期的表,datalist是字段名
-- 这里是生成并插入日期数据
INSERT INTO calendar(datelist) SELECT
adddate(
( -- 这里的起始日期,你可以换成当前日期
DATE_FORMAT("2016-1-1", '%Y-%m-%d')
),
numlist.id
) AS `date`
FROM
(
SELECT
n1.i + n10.i * 10 + n100.i * 100 + n1000.i * 1000+ n10000.i * 10000 AS id
FROM
num n1
CROSS JOIN num AS n10
CROSS JOIN num AS n100
CROSS JOIN num AS n1000
CROSS JOIN num AS n10000
) AS numlist;
2.删除num表
删除 calendar表中的数据2030年之后
DELETE from calendar where datelist>'2030-03-14'
3.将datelist设为主键
4。sql
select a.date,b.detail_id,b.instant from calendar a left join (
SELECT detail_id, DATE_FORMAT(create_date,'%Y-%m-%d') date,sum(diff_data) instant from report where detail_id in (3304) and DATE_FORMAT(create_date,'%Y-%m-%d') = '2020-12-16'
) b on a.date=b.date where a.date='2020-12-16'