获取最新的记录数据库

时间:2014-06-04 05:44:05

标签: sql-server sql-server-2008

我在数据库中有结构

 Inside   DateTime                    VehNo
  0      2014-06-03 10:51:36           1
  1      2014-06-03 09:13:57           1
  0      2014-06-03 10:35:38           2
  1      2014-06-03 10:40:38           2 

我希望像DateTime这样的输出

 Inside   DateTime                    VehNo
  0      2014-06-03 10:51:36           1     
  1      2014-06-03 10:40:38           2 

4 个答案:

答案 0 :(得分:1)

假设Inside和VehNo列是唯一的:

    SELECT inside, MAX([datetime]) as latest_datetime, vehno
    FROM mytable
GROUP BY inside, vehno;

假设只有VehNo是唯一的:

WITH max_date AS (
  SELECT max([datetime]) as max_datetime, vehno FROM mytable GROUP BY vehno
)
SELECT m.* FROM mytable m
INNER JOIN max_date md ON m.[datetime] = md.max_datetime AND m.vehno = md.vehno;

答案 1 :(得分:1)

;WITH CTE AS
(
    SELECT Inside,
           DateTime,
           VehNo,
           ROW_NUMBER() OVER( PARTITION BY Inside ORDER BY DateTime DESC) RN
    FROM <TableName>     
)
SELECT *
FROM CTE
WHERE RN = 1

答案 2 :(得分:0)

试试这个:

SELECT T1.Inside,T2.DateTime,T2.VehNo
FROM TableName T1 JOIN
    (SELECT MAX([DateTime]) as [DateTime],VehNo
     FROM TableName
     GROUP BY VehNo) T2 
   ON T1.DateTime=T2.DateTime AND T1.VehNo=T2.VehNo
ORDER BY T2.VehNo

SQL Fiddle中的示例。

<强>解释

此处,我们为每个datetime选择VehNo的最大值。然后我们将此结果与表本身相连,以获取相应的Inside

答案 3 :(得分:0)

如果你想要每个VehNo和Inside选项的最后一个DateTime,那么这应该是你的查询:

SELECT M.Inside, 
       M.DateTime, 
       M.VehNo 
FROM   mytable M 
INNER JOIN (SELECT MAX(DateTime) as max_date, 
                   Inside, 
                   VehNo  
            FROM mytable T 
            GROUP BY 
                     VehNo, Inside) 
ON M.Inside = T.Inside 
AND M.DateTime = T.max_date
AND M.VehNo = T.VehNo