DB-Fiddle
CREATE TABLE operations (
id int auto_increment primary key,
time_stamp DATE,
product VARCHAR(255),
plan_week VARCHAR(2
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;
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;