Compare values of timestamps and assign a value to each of them in case they have changed

前端 未结 2 836
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-22 09:10

DB-Fiddle

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


        
相关标签:
2条回答
  • 2021-01-22 09:47

    I would just use window functions:

    select o.*,
           (case when min(plan_week) over (partition by product) = max(plan_week) over (partition by product)
                 then 'no' else 'yes'
            end) as switched
    from operations o;
    
    0 讨论(0)
  • 2021-01-22 10:07

    If I understand your requirement correctly, your week_switch result row depends on just your product, not its timestamp.

    So compute it in a subquery.

      SELECT product,
             (CASE 
              WHEN MIN(plan_week) <> MAX(plan_week) THEN 'yes' 
              ELSE 'no' END)  AS week_switch
        FROM operations
       GROUP BY product
    

    Then JOIN that subquery to your details (fiddle).

    WITH switched AS (
      SELECT product,
             CASE
             WHEN MIN(plan_week) <> MAX(plan_week) THEN 'yes'
             ELSE 'no' END AS week_switch
        FROM operations
       GROUP BY product
    )
    SELECT
    operations.time_stamp,
    operations.product,
    operations.plan_week,
    switched.week_switch
    FROM operations
    LEFT JOIN switched ON operations.product = switched.product
    WHERE time_stamp in ('2020-01-01', '2020-03-15')
    GROUP BY 1,2;
    
    0 讨论(0)
提交回复
热议问题