比较不同时间戳的值,并确定它们是否已更改

问题描述

DB-Fiddle

CREATE TABLE operations (
    id int auto_increment primary key,time_stamp DATE,product VARCHAR(255),plan_week VARCHAR(255)
);

INSERT INTO operations
(time_stamp,product,plan_week 
)
VALUES 
("2020-01-01","Product_A","CW01"),("2020-01-01","Product_B","Product_C",("2020-03-15","CW02"),"Product_D","CW01");

预期结果

product          week_switch
Product_A           no
Product_B           yes
Product_C           yes
Product_D           no 

在以上结果中,我想检查产品plan_week是否已从一个time_stamp切换到另一个time_stamp
如果满足条件,则将yes用作值。如果没有,则应插入no

SELECT
product
FROM operations 
GROUP BY 1;

我不知道需要哪种查询来实现此目的。 你有什么主意吗?

解决方法

我认为这只是一个case表达式的聚合:

select product,(case when min(plan_week) = max(plan_week) then 'no' else 'yes' end) as flag
from operations o
group by product;
,

看起来像你想要的

select
    product,case when min(plan_week) <> max(plan_week) then 'yes' else 'no' end as week_switch
from operations
where time_stamp in ('2020-01-01','2020-03-15')
group by product

这将按产品汇总行。然后,case表达式检查plan_week中是否存在(至少)两个不同的值,并相应地设置标志。

where子句不是严格必需的。您可以删除它,具体取决于您要检查两个特定日期还是整个数据集。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...