在查询结果中将先前日期的值添加到实际日期
Posted
技术标签:
【中文标题】在查询结果中将先前日期的值添加到实际日期【英文标题】:Add value with previous date to actual date in query result 【发布时间】:2020-08-10 20:31:17 【问题描述】:DB-Fiddle:
CREATE TABLE logistics (
id int auto_increment primary key,
flow_date DATE,
flow_type VARCHAR(255),
flow_quantity INT
);
INSERT INTO logistics
(flow_date, flow_type, flow_quantity
)
VALUES
("2020-04-18", "inbound", "500"),
("2020-04-18", "outbound", "400"),
("2020-04-18", "stock", "100"),
("2020-04-19", "inbound", "800"),
("2020-04-19", "outbound", "650"),
("2020-04-19", "stock", "250"),
("2020-04-20", "inbound", "730"),
("2020-04-20", "outbound", "600"),
("2020-04-20", "stock", "380"),
("2020-04-21", "inbound", "420"),
("2020-04-21", "outbound","370"),
("2020-04-21", "stock", "430");
预期结果:
flow_date stock_yesterday inbound outbound stock_today
2020-04-18 0 500 -400 100
2020-04-19 100 800 -650 250
2020-04-20 250 730 -600 380
2020-04-21 380 420 -370 430
基本上,在我的结果中,我想展示这个时间线:stock_yesterday + inbound - outbound = stock_today
。
因此,我需要将原始表格更改如下:
a) flow_types
在结果中用作columns
。
a) stock_yesterday
是前一天的 flow_type
stock
的 flow_quantity
。
b) 所有其他flow_types
引用相同的flow_date
。
到目前为止,我想出了这个查询,但无法使它工作:
SELECT
flow_date,
(CASE WHEN flow_type = "inbound" THEN flow_quantity END) AS inbound,
(CASE WHEN flow_type = "outbound" THEN flow_quantity END) AS outbound,
(CASE WHEN flow_type = "stock" THEN flow_quantity END) AS stock_today
FROM logistics
GROUP BY 1;
它只显示inbound
。
我也不知道如何将stock_yesterday
添加到查询中。
我需要对查询进行哪些更改才能获得预期结果?
【问题讨论】:
如果你已经有了stock
,为什么还要计算它?
【参考方案1】:
您可以使用窗口函数和聚合:
select
flow_date,
sum(inbound + outbound)
over(order by flow_date rows between unbounded preceding and 1 preceding) stock_yesterday,
inbound,
outbound,
sum(inbound + outbound) over(order by flow_date) stock_today
from (
select
flow_date,
sum(case when flow_type = 'inbound' then flow_quantity else 0 end) inbound,
sum(case when flow_type = 'outbound' then -flow_quantity else 0 end) outbound
from logistics
group by flow_date
) t
order by flow_date
子查询不是绝对必要的,但它有助于缩短语法。
Demo on DB Fiddle:
flow_date |股票_昨天 |入境 |出境 |今日股票 :--------- | --------------: | ------: | --------: | ----------: 2020-04-18 | 空 | 500 | -400 | 100 2020-04-19 | 100 | 800 | -650 | 250 2020-04-20 | 250 | 730 | -600 | 380 2020-04-21 | 380 | 420 | -370 | 430【讨论】:
以上是关于在查询结果中将先前日期的值添加到实际日期的主要内容,如果未能解决你的问题,请参考以下文章