Select top rows until value in specific column has appeared twice

后端 未结 1 1540
梦毁少年i
梦毁少年i 2020-12-22 11:58

I have the following query where I am trying to select all records, ordered by date, until the second time EmailApproved = 1 is found. The second record where <

1条回答
  •  攒了一身酷
    2020-12-22 12:33

    Steps:

    1. Create a row number, rn, over all rows in case id is not in sequence.
    2. Create a row number, approv_rn, partitioned by EmailApproved so we know when EmailApproved = 1 for the second time
    3. Use a outer apply to find the row number of the second instance of EmailApproved = 1
    4. In the where clause filter out all rows where the row number is >= the value found in step 3.
    5. If there is 1 or 0 EmailApproved records available then the outer apply will return null, in which case return all available rows.
        ; with test as
        (
            select  *, 
                    rn         = row_number() over (order by Created desc),
                    approv_rn  = row_number() over (partition by EmailApproved 
                                                        order by Created desc)
            from    @Test
        )
        select  *
        from    test t
                outer apply
                (
                    select  x.rn
                    from    test x
                    where   x.EmailApproved = 1
                    and     x.approv_rn     = 2
                ) x
        where   t.rn    < x.rn or x.rn is null
        order by t.Created desc
    

    0 讨论(0)
提交回复
热议问题