6

我有一个表格,其中的数据类似于以下内容:

[ID]、[州]、[foo]、[DateCreated]、[DateUpdated]

我在这方面工作的时间越长,我的 SQL 就越难看,这告诉我我可能做错了什么。我想要的是每个州的唯一列表,只要该州的 foo 始终相同(如果该州的所有记录的 foo 都不相同,我根本不想要该州)。另外,我想合并 DateCreated 和 DateUpdated 并希望该状态的最大值。

因此,鉴于此数据:

[ID], [State], [foo], [DateCreated], [DateUpdated]
1,  MA, data1,  05/29/2012, 06/02/2012
2,  MA, data1,  05/29/2012, 06/03/2012
3,  RI, data2,  05/29/2012, NULL
4,  RI, data3,  05/29/2012, NULL
5,  NH, data4,  05/29/2012, NULL
6,  NH, data4,  05/29/2012, 06/05/2012

我只想要这些结果:

[State], [foo], [LastUpdated]
MA, data1,  06/03/2012
NH, data4,  06/05/2012

获得我所追求的最优雅的方式是什么?

4

5 回答 5

10

另一个:

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;
于 2012-07-10T17:52:43.413 回答
5

一个带有嵌套查询的简单 Group by 就足够了:

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
于 2012-07-10T17:57:19.667 回答
3

不那么优雅,但对于你可怜的 SQL 2000 灵魂来说:

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]
于 2012-07-10T17:57:06.377 回答
1

假设您使用的是 SQL Server 2005 或 >

试试这个:

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
于 2012-07-10T17:48:39.503 回答
0

试试这个:

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;
于 2018-03-08T16:28:47.007 回答