选择具有唯一2列组合的(不同)行

时间:2014-09-23 14:47:25

标签: sql sql-server tsql distinct

我想选择此表的所有行,其中前两列是唯一的([RegisterId][DeviceSerial])。目前,DISTINCT关键字也匹配RegisterName,我希望它忽略。我怎样才能做到这一点?请注意,如果这很重要,这两列将构成复合键的一部分。

SELECT DISTINCT [RegisterId]
                  ,[DeviceSerial]
                  ,[RegisterName],0 AS Contribution
              FROM [RegisterCountLogs]
              WHERE DeviceSerial = 2160563829

2 个答案:

答案 0 :(得分:4)

你可以通过

进行分组
SELECT [RegisterId]
    ,[DeviceSerial]
    , Max ([RegisterName]),0 AS Contribution
FROM [RegisterCountLogs]
WHERE DeviceSerial = 2160563829
GROUP BY [RegisterId]
    ,[DeviceSerial]

现在,如果您只想要具有RegisterId和DeviceSerial组合的行,那么您必须添加HAVING

SELECT [RegisterId]
    ,[DeviceSerial]
    , Max ([RegisterName]),0 AS Contribution
FROM [RegisterCountLogs]
WHERE DeviceSerial = 2160563829
GROUP BY [RegisterId]
    ,[DeviceSerial]
HAVING Count (*) = 1

修改

进一步思考后,您可能希望在最新/最新注册时使用该名称。

SELECT [RegisterId]
    , [DeviceSerial]
    , [RegisterName]
    , 0 AS Contribution
FROM [RegisterCountLogs]
Where RegisterId =
(
    SELECT Max ([RegisterId])
    FROM [RegisterCountLogs]
    WHERE DeviceSerial = 2160563829
    GROUP BY [DeviceSerial]
)

答案 1 :(得分:0)

您可以使用自联接来清除不需要的记录。

(未经测试的代码)

;WITH [CountLogs] as
(
    SELECT [RegisterId],[DeviceSerial],[RegisterName], 0 AS Contribution
    FROM [RegisterCountLogs]
    WHERE DeviceSerial = 2160563829
)
SELECT  RCL1.*
FROM [CountLogs] RCL1 
INNER JOIN (SELECT DISTINCT [RegisterId],[DeviceSerial] FROM [CountLogs]) RCL2 
    ON RCL1.[RegisterId] = RCL2.[RegisterId] and RCL1.[DeviceSerial] = RCL2.[DeviceSerial]