我有一个表格,其数据类似于以下内容:
我在这方面工作的时间越长,我的SQL就越有用,这告诉我,我可能做错了什么。我想要的是每个州的唯一列表,只要foo对于那个州总是相同的(如果foo对于该州的所有记录都不相同,我根本不想要那个州)。另外,我想要COALESCE 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
获得我追求的最优雅的方式是什么?
答案 0 :(得分:9)
另一个:
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;
答案 1 :(得分: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
答案 2 :(得分: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]
答案 3 :(得分: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
答案 4 :(得分: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;