2014-09-23 114 views
1

我想選擇此表的所有行,其中前兩列是唯一的([RegisterId],[DeviceSerial])。目前,DISTINCT關鍵字也匹配RegisterName,我希望它忽略它。我怎樣才能做到這一點?請注意,這兩列構成複合鍵的一部分,如果這很重要的話。選擇具有唯一2列組合的行(不同)

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

能,如果你只是把'選擇disinct' 2列部分的爲子查詢並選擇在外部查詢工作的呢? (即RegisterId主鍵,或者是(RegisterId,DeviceSerial)組合中唯一的表) – DrCopyPaste 2014-09-23 14:51:12

+0

我的SQL技能嚴重生鏽,您能發佈查詢嗎? – Chris 2014-09-23 14:51:50

+1

如果該組合具有多個「RegisterName」值,您想要哪個值? – 2014-09-23 14:51:58

回答

4

您可以通過

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

做1組現在,如果你只是想有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] 
) 
+0

我曾試過這個,它抱怨RegisterName(是一個字符串),並不知道如何阻止它抱怨..謝謝! – Chris 2014-09-23 14:52:36

+0

根據您的更新...第一個查詢工作正常,我只想要第二個,如果我想指定它只有一個匹配(而不是很多) – Chris 2014-09-23 14:53:27

+0

您可以發佈您嘗試的查詢,並且實際的錯誤你收到的消息? – 2014-09-23 14:53:30

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]