将具有前一个日期的值添加到查询结果中的实际日期

Add value with previous date to actual date in query result

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
因此,我需要像下面这样改变原来的table:

a) flow_types 在结果中用作 columns
a) stock_yesterday是前一天flow_typestockflow_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 添加到查询中。

我需要在查询中更改什么才能获得预期结果?

您可以使用 window 函数和聚合:

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  | stock_yesterday | inbound | outbound | stock_today
:--------- | --------------: | ------: | -------: | ----------:
2020-04-18 |            null |     500 |     -400 |         100
2020-04-19 |             100 |     800 |     -650 |         250
2020-04-20 |             250 |     730 |     -600 |         380
2020-04-21 |             380 |     420 |     -370 |         430