Say I have a table like
store | date | is_open |
---|---|---|
Bay | 1/1/2022 | true |
Bay | 1/2/2022 | true |
Bay | 1/3/2022 | true |
Bay | 1/4/2022 | false |
Bay | 1/5/2022 | false |
Bay | 1/6/2022 | false |
Bay | 1/7/2022 | true |
Bay | 1/8/2022 | true |
Bay | 1/9/2022 | true |
Walmart | 1/7/2022 | true |
Walmart | 1/8/2022 | false |
Walmart | 1/9/2022 | true |
I want them to use partition by and get the rank of the group such as
store | date | is_open | group |
---|---|---|---|
Bay | 1/1/2022 | true | 1 |
Bay | 1/2/2022 | true | 1 |
Bay | 1/3/2022 | true | 1 |
Bay | 1/4/2022 | false | 2 |
Bay | 1/5/2022 | false | 2 |
Bay | 1/6/2022 | false | 2 |
Bay | 1/7/2022 | true | 3 |
Bay | 1/8/2022 | true | 3 |
Bay | 1/9/2022 | true | 3 |
Walmart | 1/7/2022 | true | 1 |
Walmart | 1/8/2022 | false | 2 |
Walmart | 1/9/2022 | true | 3 |
I started trying partition by store
and is_open
but really confuse what to use in order by clause any help would be appreciated.
Advertisement
Answer
You can use LAG() to detect start of a group.
with cte AS ( SELECT t.*, case when lag(is_open) OVER (PARTITION BY store ORDER BY date) = is_open then 0 else 1 end sflag FROM yourTable t ) SELECT store, date, is_open, sum(sflag) over(PARTITION BY store ORDER BY date) grp FROM cte ORDER BY store, date;