SQL两列guid没有重复

时间:2016-06-03 20:42:50

标签: sql sql-server stored-procedures guid

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

Inspection Guid, SensorData Guid, DateTime

我想获得一个检查Guid,SensorDataGuid,DateTime的表格,但没有重复的检查指南。

From(为方便起见,我缩短了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

按日期时间排序。

非常感谢你的帮助。

3 个答案:

答案 0 :(得分:0)

USE 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

答案 1 :(得分:0)

实际上你想要的并不是所谓的。

以这两条记录为例:

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

答案 2 :(得分:0)

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]的分区可确保每个日期时间的分区都是唯一的。