接到一个任务,要计算日环比的情况。
16、查询销售额日环比情况
日环比: (今日-昨日)/ 昨日 的一个比率情况。
1,建表
DROP TABLE IF EXISTS sale;
create table sale(id int not null AUTO_INCREMENT,record_date date,ammount int default 0,primary key(id)
);
2,插入数据
INSERT INTO sale VALUES
(1, '2020-01-01', 1000),
(2, '2020-01-02', 2500),
(3, '2020-01-03', 2000),
(4, '2020-01-04', 3000),
(5, '2020-01-05', 2900),
(6, '2020-01-06', 3100),
(7, '2020-01-07', 3300);
3,sql
1,关联查询的方式:
SELECT cur.record_date,cur.ammount AS current_ammount, pre.ammount AS previous_ammount, (cur.ammount - pre.ammount) AS diffValue,(cur.ammount - pre.ammount)/ pre.ammount AS daily_growth_rateFROM sale cur, sale preWHERE cur.record_date = DATE_ADD(pre.record_date, INTERVAL 1 DAY);-- 或者用-- WHERE 1 = DATEDIFF(cur.record_date, pre.record_date);
2,用变量的方式:
错误位置:
-- 放在赋值后面,就跟当天比了,公式变成: (当天 - 昨天 )/当天
SELECT *, (@diff:=ammount-@pre) AS diffValue,@pre:=ammount AS pre,
(@diff / @pre) AS daily_growth_rate
FROM sale ORDER BY record_date;
正确位置:
-- 要放前面,但是还是有一个问题,会有第一条,没有去除, 这个麻烦些,还得去除第一条
SELECT *, (@diff:=ammount-@pre) AS diffValue,(@diff / @pre) AS daily_growth_rate, @pre:=ammount AS pre
FROM sale ORDER BY record_date;
第一条也算进去了。跟最后一条进行相比较了。
去除第一条:
SELECT record_date, ammount AS current_ammount,
pre AS previous_ammount, daily_growth_rate
FROM (
SELECT *, (@diff:=ammount-@pre) AS diffValue,(@diff / @pre) AS daily_growth_rate, @pre:=ammount AS pre
FROM sale ORDER BY record_date
) AS temp WHERE record_date
NOT IN (SELECT MIN(record_date) min_record_date FROM sale);
总结:
日环比,这个用变量的方式,就显得画蛇添足了,直接用sql也更好理解。不过,当做练习还是可以的。
上一篇: 《mysql 查询实战3-解答》
下一篇: 《mysql 重复单号 统计》