用于返回每个ID的最新记录的SQL查询

时间:2013-03-14 02:11:27

标签: sql sql-server sql-server-2008 tsql

我有一个具有以下结构的表。

LocId    Value1    Value1Date                
.............................................
1        50        2012-10-20 14:21:00.000      
1        70        2012-10-21 14:21:00.000      
1        90        2012-10-22 14:21:00.000      
1        100       2012-10-23 14:21:00.000    
2        20        2012-10-20 14:21:00.000       
2        40        2012-10-21 11:21:00.000      
2        70        2012-10-22 14:21:00.000     
2        80        2012-10-23 14:21:00.000 
3        50        2012-10-20 14:21:00.000       
3        70        2012-10-21 11:21:00.000      
3        80        2012-10-22 14:21:00.000      
3        90        2012-10-23 14:21:00.000

我想要实现的是,对于每个[LocId],我需要最新日期时间的[Value1](即2012-10-23)。返回的表应如下所示:

LocId    Value1    Value1Date                
.............................................
1        100       2012-10-23 14:21:00.000
2        80        2012-10-23 14:21:00.000
3        90        2012-10-23 14:21:00.000

有人可以请一只手吗?感谢

4 个答案:

答案 0 :(得分:4)

你可以像这样使用排名而不是:

select * from
(select locid, value1, value1date, 
  rank() over (partition by locid order by value1date desc) as rank
  from table1) t
where t.rank=1

请参阅SqlFiddle

答案 1 :(得分:2)

可以使用Common Table ExpressionWindow Function

来实现
WITH records
AS
(
    SELECT  LocID, VAlue1, Value1Date,
            ROW_NUMBER() OVER (PARTITION BY LocID ORDER BY Value1Date DESC) rn
    FROM    TableName
)
SELECT  LocID, VAlue1, Value1Date
FROM    records
WHERE   rn = 1

答案 2 :(得分:1)

这种方法可行。

select locid, value1, value1date
from yourtable join
(select locid id, max(value1date) maxdate
from yourtable
group by locid) temp on id = locid 
and value1date = maxdate

答案 3 :(得分:0)

这是执行您要查找的内容的mysql查询。我真的不知道其他SQL。

SELECT * FROM table WHERE LocID = n ORDER BY Value1Date DESC LIMIT 1;

如果您正在查询某个程序,可以使用:

SELECT LocID FROM table ORDER BY LocID DESC LIMIT 1;

获取ID的总数(假设它们是连续的),然后将它放在循环中以获取所有最近的日期。

希望有所帮助。