2015-12-07 64 views
0

我有一個表值如何使用DISTINCT關鍵字與ORDER BY

ID Number 
1 6 
2 6 
3 7 
4 7 
5 1 
6 1 
7 2 
8 2 

我寫了一個選擇查詢的不同數字

SELECT DISTINCT Number FROM Table 

我喜歡

ID Number 
1 1 
2 2 
3 6 
4 7 
輸出

但我想輸出像

ID Number 
1 6 
2 7 
3 1 
4 2 

我怎樣才能帶來這樣的輸出?

+3

'SELECT FROM Table' DISTINCT數只會返回一列,但你的狀態,你有一個輸出有兩列。所以無論你的SQL是錯誤的還是你的示例輸出都是錯誤的。 –

回答

2

您可以使用窗口函數像ROW_NUMBER

WITH cte AS 
(
    SELECT Number, MAX(ID) AS max_ID 
    FROM #Tab 
    GROUP BY Number 
) 
SELECT ROW_NUMBER() OVER(ORDER BY max_ID) AS ID, Number 
FROM cte 
ORDER BY max_ID 

LiveDemo

輸出:

╔════╦════════╗ 
║ ID ║ Number ║ 
╠════╬════════╣ 
║ 1 ║  6 ║ 
║ 2 ║  7 ║ 
║ 3 ║  1 ║ 
║ 4 ║  2 ║ 
╚════╩════════╝ 
+1

。,謝謝你解決了我的問題 –

0

所以,你要刪除重複Numbers並保留通過排序ID

一種可能的方式是使用ROW_NUMBER

DECLARE @T TABLE ([ID] int, [Number] int); 

INSERT INTO @T ([ID], [Number]) VALUES 
    (1, 6), 
    (2, 6), 
    (3, 7), 
    (4, 7), 
    (5, 1), 
    (6, 1), 
    (7, 2), 
    (8, 2); 

WITH 
CTE 
AS 
(
    SELECT 
     ID 
     ,Number 
     ,ROW_NUMBER() OVER (PARTITION BY Number ORDER BY ID) AS rn 
    FROM @T AS T 
) 
SELECT 
    ID 
    ,Number 
FROM CTE 
WHERE rn = 1 
ORDER BY ID; 

結果

ID Number 
1 6 
3 7 
5 1 
7 2