计算多个时间戳之间的差异
Posted
技术标签:
【中文标题】计算多个时间戳之间的差异【英文标题】:Calculate difference between multiple timestamps 【发布时间】:2020-10-19 13:18:23 【问题描述】:DB-Fiddle:
CREATE TABLE sales (
id int auto_increment primary key,
time_stamp DATE,
product VARCHAR(255),
sales_quantity INT
);
INSERT INTO sales
(time_stamp, product, sales_quantity
)
VALUES
("2020-01-14", "Product_A", "100"),
("2020-01-14", "Product_B", "300"),
("2020-01-14", "Product_C", "600"),
("2020-01-15", "Product_A", "100"),
("2020-01-15", "Product_B", "350"),
("2020-01-15", "Product_C", "600"),
("2020-01-16", "Product_A", "130"),
("2020-01-16", "Product_B", "350"),
("2020-01-16", "Product_C", "670"),
("2020-01-16", "Product_D", "400"),
("2020-01-17", "Product_A", "130"),
("2020-01-17", "Product_B", "350"),
("2020-01-17", "Product_C", "700"),
("2020-01-17", "Product_D", "450");
预期结果:
time_stamp difference
2020-01-14 0
2020-01-15 50 = (100+350+600) - (100+300+600)
2020-01-16 500 = (130+350+670+400) - (100+350+600)
2020-01-17 80 = (130+350+700+450) - (130+350+670+400)
在上面的结果中,我想计算多个timestamps
之间的sales_quantiy
的difference
。
我试着用这个查询:
SELECT
time_stamp,
(SUM(t1.time_stamp_01) - SUM(t1.time_stamp_02)) AS difference
FROM
(SELECT
time_stamp,
SUM(CASE WHEN time_stamp = '2020-01-14' THEN sales_quantity ELSE 0 END) AS time_stamp_01,
SUM(CASE WHEN time_stamp = '2020-01-15' THEN sales_quantity ELSE 0 END) AS time_stamp_02
FROM sales
GROUP BY 1) t1
GROUP BY 1;
但是,它不知何故不会计算timestamps
之间的difference
,它也仅限于两个timestamps
。
我需要如何修改query
才能得到预期的结果?
【问题讨论】:
【参考方案1】:如果你运行的是 mysql 8.0,你可以使用聚合和lag()
:
select time_stamp,
sum(sales_quantity)
- lag(sum(sales_quantity), 1, sum(sales_quantity)) over(order by time_stamp) diff
from sales
group by time_stamp
order by time_stamp
这适用于 MySQL 8.0,但不适用于 MariaDB 10.3(这是您的小提琴使用的)。您可以使用:
select time_stamp, sum_sales_quantity - coalesce(lag(sum_sales_quantity) over(order by time_stamp), sum_sales_quantity) diff
from (
select time_stamp, sum(sales_quantity) sum_sales_quantity
from sales
group by time_stamp
) t
order by time_stamp
【讨论】:
以上是关于计算多个时间戳之间的差异的主要内容,如果未能解决你的问题,请参考以下文章
Oracle - 计算时间戳之间的差异大于 1 小时的时间戳
带有 UNIX 时间戳的 MySQL 表 - 按时间戳排序并计算一行与前一行之间的差异