我有一个包含ID,Title,Date
的表模式和数据看起来像这样:
1 The title1 2011-04-05 00:00:00.000
2 Another title 2011-04-11 00:00:00.000
3 The title1 2011-04-11 16:49:23.633
4 The title1 2011-04-11 00:00:00.000
我需要帮助sql给我每个标题的最新日期。 所以上述数据的输出是
2 Another title 2011-04-11 00:00:00.000
3 The title1 2011-04-11 16:49:23.633
答案 0 :(得分:5)
select id,title,date from [schema]
where title in (select title from [schema] group by title having date=max(date))
试试这个
答案 1 :(得分:2)
在线图书中查看Max和group by
答案 2 :(得分:2)
select mytable.Title, MAX(mytable.Date)
from mytable
group by mytable.Title
答案 3 :(得分:1)
看看包含Aggregated Column's Related Values,有几种方法可以实现这个目标
一种方法是
select t1.* from(
select Title, Max(Date) as MaxDate
From YourTable
group by Title) t2
join YourTable t1 on t2.Title = t1.Title
and t1.Date = t2.MaxDAte
答案 4 :(得分:1)
假设您的表名为mytable
:
select
tbl.ID, tbl.Title, tbl.Date
from
mytable tbl join
(select Title, max(Date) Date
from mytable) maxes on tbl.Date = maxes.Date and tbl.Title = maxes.Title
答案 5 :(得分:1)
至少假设SQL Server 2005:
SELECT ID, Title, [Date]
FROM (SELECT ID, Title, [Date],
ROW_NUMBER() OVER(PARTITION BY Title ORDER BY [Date] DESC) AS RowNum
FROM YourTable
) t
WHERE t.RowNum = 1