2015-09-11 53 views
0

我有這個表:加入兩個表返回唯一的KeyID

CREATE TABLE SETTINGS 
    ([AccountNumber] int, [KeyID] int, [KeyValue] varchar(50)) 
; 

INSERT INTO SETTINGS 
    ([AccountNumber], [KeyID], [KeyValue]) 
     VALUES 
     (null, 1, 'welcome'), 
     (null, 2, 'defaultaccount'), 
     (null, 3, 'greetings'), 
     (1234567, 2,'customaccount'); 
; 

enter image description here

我試圖做到的是用獨特KeyID返回行。會出現兩次出現相同的KeyID的情況,但一行AccountNumber不會爲空。在這種情況下,我想返回AccountNumber不爲空的行。

輸出,我試圖讓:

enter image description here

爲了讓輸出我創建每個記錄的rownumber,然後試圖加入的表,其中rownumber=1。但我不知道如何排除KeyID的匹配,但AccountNumber is null

這是我的代碼。

;WITH singleRow AS (
SELECT * , ROW_NUMBER() OVER (PARTITION BY KEYID ORDER BY KEYID) as rownum 
FROM SETTINGS); 

SELECT s.KeyID FROM SETTINGS s 
    JOIN singleRow r 
    ON s.keyid = r.keyid 
    AND r.rownum = 1 

我應該在這種情況下使用兩個臨時表嗎?在第一個臨時表中存儲具有唯一的所有行KeyID其中AccountNumber is null。而在第二家店只是在那裏排AccountNumber is not null。然後加入桌子?看起來我太過於複雜了。

這是SQL FIDDLE

回答

2

SqlFiddleDemo

;WITH singleRows AS 
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY keyid ORDER BY AccountNumber DESC) 
     AS rownum 
    FROM settings 
) 
SELECT [AccountNumber], [KeyID], [KeyValue] 
FROM singleRows 
WHERE rownum = 1; 
+0

謝謝。我現在看到我的問題。 – smr5

0

SELECT * FROM(SELECT 等級()OVER(PARTITION BY KEYID ORDER BY賬戶號碼DESC)RNK,* AS ROWNUM FROM設置)t其中t.rnk = 1