SQL 两列 guids 没有重复

SQL Two columns of guids no duplicates

我正在通过观看 YouTube 来学习 SQL,我正在努力实现以下目标。 我有一个 table 三列

Inspection Guid, SensorData Guid, DateTime

我想要 table Inspection Guid、SensorDataGuid、DateTime 但没有重复的 Inspection Guid。

来自(为方便起见,我缩短了 Guids)

6E814118    DA875776    2016-05-25 14:59:17.523
6E814118    BAEB255D    2016-05-25 14:59:17.523
4B7D4E90    BB717852    2016-05-25 14:58:46.260
06BB9435    2321EDD6    2016-05-25 14:58:16.870
06BB9435    D4168F8B    2016-05-25 14:58:16.870
8D9A8502    3EED26BE    2016-05-25 14:57:47.400
5C9AA885    77D342DD    2016-05-25 14:57:15.217
5C9AA885    43DEF213    2016-05-25 14:57:15.217

6E814118    DA875776    2016-05-25 14:59:17.523
4B7D4E90    BB717852    2016-05-25 14:58:46.260
06BB9435    2321EDD6    2016-05-25 14:58:16.870
8D9A8502    3EED26BE    2016-05-25 14:57:47.400
5C9AA885    77D342DD    2016-05-25 14:57:15.217

按日期时间排序。

非常感谢您的帮助。

使用ROW_NUMBER()根据DATE选择第一个GUID然后ORDER BY显示。

SELECT *
FROM (
        SELECT [Inspection Guid], 
               [SensorData Guid], 
               [DateTime],
               ROW_NUMBER() OVER (PARTITION BY [Inspection Guid] 
                                  ORDER BY [DateTime] DESC) rn
        FROM YourTable
      ) T
WHERE rn = 1
ORDER BY [DateTime] DESC

你要的其实问的不可以

以这2条记录为例:

06BB9435    2321EDD6    2016-05-25 14:58:16.870
06BB9435    D4168F8B    2016-05-25 14:58:16.870

如果您只想显示 06BB9435 一次,您会如何决定要显示其他哪些数据?您必须决定为每个重复的 GUID 显示哪个日期。如果您想要最近日期和按字母顺序排列最高的 SensorData,那么您可以这样做:

SELECT [Inspection Guid], MAX([SensorData Guid]), MAX([DateTime])
FROM YourTable
GROUP BY [Inspection Guid]
ORDER BY MAX([DateTime]) DESC
WITH duplicates AS
(
    SELECT
        [Inspection Guid],
        [SensorData Guid],
        [DateTime],
        ROW_NUMBER() OVER
        (
            PARTITION BY [Inspection Guid], [DateTime]
            ORDER BY [SensorData Guid]
        ) AS rn
    FROM YourTable
)
SELECT *
FROM duplicates
WHERE rn = 1

按 2 个字段 [Inspection Guid][DateTime] 的分区确保每个日期时间的分区都是唯一的。