SQL - Ugly combination of GROUP BY and COALESCE

后端 未结 5 1750
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

    A simple Group by with nested queries should suffice:

    Select State, coalesce(max_created,max_updated) from (
      Select State, min(foo) as min_foo, max(foo) as max_foo, 
        max(DateCreated) as max_created,
        max(DateUpdated) as max_updated
      From Data
      Group by State)
     Where min_foo = max_foo
    

提交回复
热议问题