Search code examples
mysqlsqlrelational-databaseamazon-redshiftsql-timestamp

How do I test the sequence of values of a column (based on timestamps) within each group in SQL?


I have colA, colB, colC in tableA where colC is a timestamp variable.

there are 5 possible values for colB.

select distinct(colB) from tableA; 

x
y
z

I want to make sure that for each value of colA, the record(s) with colB='a' has earlier timestamps than record(s) with colB='b' and so on. So, colB='b' records should come after colB='a' and colB='c' records should come after colB='b' for each value of colA

I need a SQL query for the same


Solution

  • If I understand correctly, you can use group by and having:

    select cola
    from tableA
    group by cola
    having max(case when colb = 'a' then timestamp end) < min(case when colb = 'b' then timestamp end) and
           max(case when colb = 'b' then timestamp end) < min(case when colb = 'c' then timestamp end) and
          . . .