【问题标题】:Compare values of different time-stamps and identify if they have changed比较不同时间戳的值并确定它们是否已更改
【发布时间】:2020-12-20 15:49:13
【问题描述】:

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", "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;

我不知道我需要什么样的查询来实现这一点。 你有什么想法吗?

【问题讨论】:

    标签: mysql sql group-by max min


    【解决方案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 子句不是绝对必要的。您可以删除它,具体取决于您是要检查两个特定日期还是整个数据集。

    【讨论】:

    【解决方案2】:

    我认为这只是使用case 表达式的聚合:

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

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多