我怎样才能从表格中选择最新的条目

时间:2011-06-27 06:43:58

标签: tsql

我在MS SQL Server 2008数据库中有一个包含这样的作业的表:

J_ID      J_Name       J_ReadDate                  J_I_ID
`````````````````````````````````````````````````````````
01        Job1        2011-06-26 01:00:12.153      1
02        Job2        2011-06-25 01:00:07.103      1
03        Job3        2011-06-25 01:00:07.103      2
04        Job4        2011-06-25 01:00:07.103      3
05        Job1        2011-06-26 01:00:07.103      1
06        Job2        2011-06-26 01:00:08.103      2
07        Job1        2011-06-26 01:00:08.103      2

现在我想只选择最新的工作,无论条目多大。所以在我的例子中,它希望得到这个结果(由J_ReadDate DESC排序):

J_ID      J_Name       J_ReadDate                  J_I_ID
`````````````````````````````````````````````````````````
06        Job2        2011-06-26 01:00:08.103      2
07        Job1        2011-06-26 01:00:08.103      2
05        Job1        2011-06-26 01:00:07.103      1
03        Job3        2011-06-25 01:00:07.103      2
04        Job4        2011-06-25 01:00:07.103      3

我怎样才能做到这一点?我不能说,条目之间的时差总是一天。

1 个答案:

答案 0 :(得分:5)

以下内容将为您提供所需资讯。

SELECT J_ID, J_Name, J_ReadDate, J_I_ID
FROM (
  SELECT J_ID, J_Name, J_ReadDate, J_I_ID,
         ROW_NUMBER() OVER (PARTITION BY J_Name ORDER BY J_ReadDate DESC) AS RN
  FROM jobs
) J
WHERE J.RN = 1
ORDER BY J_ReadDate DESC