根据一列选择不同的记录组,然后按日期时间

时间:2016-03-03 10:38:07

标签: sql sql-server tsql select

我想根据一个列值选择不同的记录组,然后按日期时间排序。

例如,我有这个数据表

+----+---------+-------+---------------------------+
| id | Name    | Index | DateTime                  |
+----+---------+-------+---------------------------+
|  3 | Index   | 1     | 2016-03-03 12:03:15.353   |
|  4 | Index   | 1     | 2016-03-01 12:03:15.353   |
|  5 | Middle  | 2     | 2016-03-03 12:03:15.353   |
|  6 | Little  | 3     | 2016-03-03 12:03:15.353   |
|  7 | Thumb   | 4     | 2016-03-03 12:03:15.353   |
|  8 | Thumb   | 4     | 2016-03-01 12:03:15.353   |
+----+---------+-----------------------------------+

我想得到这样的结果:

+----+---------+-------+---------------------------+
| id | Name    | Index | DateTime                  |
+----+---------+-------+---------------------------+
|  3 | Index   | 1     | 2016-03-03 12:03:15.353   |
|  5 | Middle  | 2     | 2016-03-03 12:03:15.353   |
|  6 | Little  | 3     | 2016-03-03 12:03:15.353   |
|  7 | Thumb   | 4     | 2016-03-03 12:03:15.353   |
+----+---------+-----------------------------------+

+----+---------+-------+---------------------------+
| id | Name    | Index | DateTime                  |
+----+---------+-------+---------------------------+    
|  4 | Index   | 1     | 2016-03-01 12:03:15.353   |    
|  8 | Thumb   | 4     | 2016-03-01 12:03:15.353   |
+----+---------+-----------------------------------+

考虑一个指纹系统,它可以保存所有指纹而不会覆盖同一个手指重新注册,我想要检索已注册的最新手指以及手指重新注册多次时的历史记录。

我尝试了这个根据索引返回不同记录的查询:

SELECT a.*
FROM    Fingerprint a
INNER JOIN 
      (SELECT DISTINCT [Index], MIN(Id) as id
       FROM Fingerprint 
       GROUP BY [Index]) AS b
ON a.[Index] = b.[Index] 
    AND a.id = b.id

WHERE [RefNumber] = '00000'

ORDER BY [LastUpdatedOn] DESC

我怎样才能实现这个sql查询?

我在这里发现了类似的问题: Get Distinct rows according to one column and order by date

使用LINQ检索没有历史记录的不同记录。

2 个答案:

答案 0 :(得分:1)

逻辑:

使用Partition函数根据id列计算排名,然后按排名排序,然后按id列上的顺序

select [id], [Name], [Index], [DateTime] from
(
 Select 
     *, 
    ROW_NUMBER() OVER (PARTITION by Name order by id asc) as rr
 from Fingerprint
 ) t
order by rr asc, id asc

输出屏幕截图:

enter image description here

答案 1 :(得分:0)

最简单的方法可能是使用窗口row_number()函数:

SELECT [id], [Name], [Index], [DateTime]
FROM   (SELECT [id], [Name], [Index], [DateTime],
               ROW_NUMBER() OVER (PARTITION BY [Name] ORDER BY [DateTime] AS rn
        FROM   Fingerprint) f
WHERE   rn = 1