Search code examples
sqlazureazure-databricks

SQL: Finding min, max date with repeated value


If I have data like below and I need to find min and max date of each promotion order by date Please help me for SQL script

Data:
Sample Data

Data:   
month           promotion
31/01/2019          A
28/02/2019          A
31/03/2019          B
30/04/2019          C
31/05/2019          C
30/06/2019          C
31/07/2019          C
31/08/2019          C
30/09/2019          B
31/10/2019          B
30/11/2019          B
31/12/2019          B

need result:
Need result

need result:        
min_month   max_month   promotion
31/01/2019  28/02/2019  A
31/03/2019  31/03/2019  B
30/04/2019  31/08/2019  C
30/09/2019  31/12/2019  B

result i got: incorrect
result i got: incorrect

min_month   max_month   promotion
31/01/2019  28/02/2019  A
31/03/2019  31/12/2019  B
30/04/2019  31/08/2019  C

Thank you

My script

select promotion, min(month) min_month, max(month) max_month  
from table  
group by promotion

Solution

  • This is form of GAPS and ISLAND problem. If your DBMS supports window functions, You may try below query -

    select min(month) min_month, max(month) max_month, promotion
    from (select promotion,
                 month,
                 rank() over(order by month) seqnum1,
                 rank() over(partition by promotion order by month) seqnum2
          from table) t
    group by promotion, seqnum1 - seqnum2;