SQL - Ugly combination of GROUP BY and COALESCE

后端 未结 5 1748
Happy的楠姐
Happy的楠姐 2021-01-18 08:01

I have a table with data similar to the following:

[ID], [State], [foo], [DateCreated], [DateUpdated]

The longer I work on this, the uglier my SQL is getti

5条回答
  •  北海茫月
    2021-01-18 08:23

    Assuming you are using SQL Server 2005 or >

    Try this:

    WITH Data AS
    (
        SELECT  *,
            COALESCE([DateCreated], [DateUpdated]) AS LastUpdated,
            ROW_NUMBER() OVER(PARTITION BY State ORDER BY COALESCE([DateCreated], [DateUpdated]) DESC) Position
          FROM  a
         WHERE NOT EXISTS
         (
            SELECT  1 
                FROM     b
             WHERE  a.State = b.State
                AND a.foo <> b.foo
         )
    )
    SELECT State, foo, LastUpdated
      FROM Data
     WHERE Positon = 1
    

提交回复
热议问题