CREATE TABLE operations (
id int auto_increment primary key,
time_stamp DATE,
product VARCHAR(255),
quantity INT
);
INSERT INTO operations
(time_stamp, product, quantity
)
VALUES
("2020-01-01", "Product_A", "600"),
("2020-01-01", "Product_B", "400"),
("2020-01-01", "Product_C", "700"),
("2020-03-15", "Product_A", "300"),
("2020-03-15", "Product_B", "500"),
("2020-03-15", "Product_C", "900"),
("2020-03-15", "Product_D", "150");
预期结果:
Product 2020-01-01 2020-03-15 difference
Product_A 600 300 -300
Product_B 400 500 100
Product_C 700 900 200
Product_D 0 150 150
在以上结果中,我想显示每个quantity
的每种产品的time_stamp
,并在列difference
的{{1}}之间计算quantities
。
到目前为止,我想出了类似的方法,但无法使其起作用:
difference
您是否知道我需要更改查询以实现预期结果?
答案 0 :(得分:0)
您可以进行条件聚合:
select
product,
sum(case when time_stamp = '2020-01-01' then quantity else 0 end) quanty_20200101,
sum(case when time_stamp = '2020-03-15' then quantity else 0 end) quanty_20200315,
sum(case when time_stamp = '2020-03-15' then quantity else -quantity end) diff
from operations
where time_stamp in ('2020-01-01', '2020-03-15')
group by product