我想获得有关返回前一天值的查询的帮助吗?
假设我有一个两列的表格,其中一个是日期,另一个是收入(数字)。我想获取表格中每一天的前一天收入。
我尝试运行此查询,但它只向我返回当天而不是前一天的值
SELECT
date(u.creation_date),
COUNT(CASE WHEN date(u.creation_date) = date_sub(date(u.creation_date), INTERVAL 1 DAY) THEN 1 ELSE 0 END) "yestarday"
FROM user u
GROUP BY 1
ORDER BY 1;
我希望输出 日期,收入,前一天的收入
09/04 , 1, 0
09/05 , 2, 1
09/06 , 1, 2
09/07 , 5, 1
09/08 , 4, 5
答案 0 :(得分:1)
如果您没有mysql 8或更高版本,则需要使用子查询或联接。而且我不知道您为什么使用计数来求和。
create table t
(dt date, revenue int);
insert into t values
('2019-01-01',1),
('2019-01-01',1),
('2019-01-02',1);
select dt, sum(revenue) today,
(select sum(revenue) from t t1 where t1.dt = t.dt - 1) yesterday
from t
group by dt;
select t.dt, sum(t.revenue) today,
y.revenue as yesterday
from t
left join (select dt,sum(revenue) revenue from t group by dt) y on y.dt = t.dt -1
group by t.dt;
+------------+-------+-----------+
| dt | today | yesterday |
+------------+-------+-----------+
| 2019-01-01 | 2 | NULL |
| 2019-01-02 | 1 | 2 |
+------------+-------+-----------+
2 rows in set (0.00 sec)
答案 1 :(得分:0)
如果表中没有空格,则可以执行以下操作:
SELECT DATE(u.creation_date) + INTERVAL 1 DAY,
COUNT(*) as yesterday,
SUM(u.revenue) as yesterday_revenue
FROM user u
GROUP BY 1
ORDER BY 1;