'SQL CODE: Question about CASE statement that looks at a YYYMM, looks back 12 months. Then tags 0 if there was a date or else 1

Good Morning. I am using TOAD. I wrote this code and it works as intended. I wanted the Min YYYYMM after 201801 to be tagged 1 and everything else 0.

  • 201712 MARKET 0
  • 201801 MARKET 1
  • 201802 MARKET 0
  • 201905 MARKET 0

.

WITH

T1 AS (SELECT DISTINCT STORE STORE
, MIN(YYYYMM) MIN_YYYYMM


FROM STORE_ORDERS

WHERE YYYYMM >= '201801'
AND FRUIT = 'APPLE'

GROUP BY STORE 
)

SELECT DISTINCT T2.YYYY YYYY
, T2.YYYYMM YYYYMM
, T2.STORE STORE
, T2.FRUIT FRUIT
, CASE WHEN T1.STORE = T2.STORE 
    AND T1.MIN_YYYYMM = T2.YYYYMM
    THEN 1 ELSE 0 END FIRST_ORDER

FROM STORE_ORDERS T2

INNER JOIN T1
ON T2.STORE = T1.STORE

WHERE T2.FRUIT = 'APPLE'

ORDER BY T2.STORE
, T2.YYYYMM ASC 

My question lies in the second ask for the code. I need to look at that '1' date and see if there was a date within 12 months before that date. If there was then it should be a 0 if there wasn't it should be a '1' (like the example below)

  • 201712 MARKET 0
  • 201801 MARKET 0
  • 201802 MARKET 0
  • 201905 MARKET 1


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source