SQL - Ugly combination of GROUP BY and COALESCE

后端 未结 5 1749
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
    
    0 讨论(0)
  • 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 <YOUR-TABLE> a
         WHERE NOT EXISTS
         (
            SELECT  1 
                FROM    <YOUR-TABLE> b
             WHERE  a.State = b.State
                AND a.foo <> b.foo
         )
    )
    SELECT State, foo, LastUpdated
      FROM Data
     WHERE Positon = 1
    
    0 讨论(0)
  • 2021-01-18 08:25

    Try this:

    select state_name,foo,max(dateUpdated) from state where state_name in (select state_name from state group by state_name having count(distinct foo)=1) group by state_name,foo;
    
    0 讨论(0)
  • 2021-01-18 08:30

    Another one:

    http://sqlfiddle.com/#!6/fd219/1

    SELECT
      t.State,
      MAX(t.foo),
      MAX( COALESCE( t.DateUpdated, t.DateCreated ))
    FROM t
    GROUP BY t.State
    HAVING COUNT(DISTINCT t.foo) = 1;
    
    0 讨论(0)
  • 2021-01-18 08:39

    Not as elegant, but for you poor SQL 2000 souls:

    SELECT T1.State, T2.Foo, T1.LastUpdated
    FROM (
        SELECT State, MAX([ID]) AS [ID], 
            MAX(COALESCE(DateUpdated, DateCreated)) AS LastUpdated
        FROM YourTable
        GROUP BY State
        HAVING COUNT(DISTINCT Foo) = 1
    ) T1 
    INNER JOIN YourTable T2 ON T1.State = T2.State AND T1.[ID] = T2.[ID]
    
    0 讨论(0)
提交回复
热议问题