Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 比较两个时间戳的值并计算差异_Mysql_Sql - Fatal编程技术网

Mysql 比较两个时间戳的值并计算差异

Mysql 比较两个时间戳的值并计算差异,mysql,sql,Mysql,Sql,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", "

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

在上面的结果中,我想显示每个
时间戳的每个产品的
数量
,并在
差异
列中计算
数量
之间的
差异

到目前为止,我想出了类似的方法,但无法实现:

SELECT
product,
'2020-01-01' AS time_stamp_01,
'2020-01-15' AS time_stamp_02,
SUM(quantity) As quantity
FROM operations
GROUP BY 1,2;

您知道我需要在查询中更改什么以获得预期结果吗?

您可以执行条件聚合:

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

您可以执行条件聚合:

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