比较不同时间戳的值并确定它们是否已更改
Compare values of different time-stamps and identify if they have changed
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", "CW01"),
("2020-01-01", "Product_C", "CW01"),
("2020-03-15", "Product_A", "CW01"),
("2020-03-15", "Product_B", "CW02"),
("2020-03-15", "Product_C", "CW02"),
("2020-03-15", "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;
我不知道我需要什么样的查询来实现这个。
你有什么想法吗?
看起来你想要:
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
子句不是绝对必要的。您可以删除它,具体取决于您是要检查两个特定日期还是整个数据集。
我认为这只是使用 case
表达式的聚合:
select product,
(case when min(plan_week) = max(plan_week) then 'no' else 'yes' end) as flag
from operations o
group by product;
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", "CW01"),
("2020-01-01", "Product_C", "CW01"),
("2020-03-15", "Product_A", "CW01"),
("2020-03-15", "Product_B", "CW02"),
("2020-03-15", "Product_C", "CW02"),
("2020-03-15", "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;
我不知道我需要什么样的查询来实现这个。 你有什么想法吗?
看起来你想要:
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
子句不是绝对必要的。您可以删除它,具体取决于您是要检查两个特定日期还是整个数据集。
我认为这只是使用 case
表达式的聚合:
select product,
(case when min(plan_week) = max(plan_week) then 'no' else 'yes' end) as flag
from operations o
group by product;