2010-06-15 77 views
1

篩選的結果我有一個表像下面這樣:掌握子查詢

ID Name Color 
------------ 
1 Bob Blue 
2 John Yellow 
1 Bob Green 
3 Sara Red 
3 Sara Green 

我想要做的是返回由此返回以下數據結果的過濾列表:

ID Name Color 
------------ 
1 Bob Blue 
2 John Yellow 
3 Sara Red 

即我想每個用戶返回1行。 (我不介意爲特定用戶返回哪一行 - 我只需要[ID]是唯一的。)我已經有一些工作,但真的很慢,我創建一個臨時表,添加所有ID,然後使用「OUTER APPLY」從同一張表中選擇前1,即

CREATE TABLE #tb 
( 
    [ID] [int] 
) 

INSERT INTO #tb 
select distinct [ID] from MyTable 

select 
    T1.[ID], 
    T2.[Name], 
    T2.Color 
from 
    #tb T1 
    OUTER APPLY 
    (
     SELECT TOP 1 * FROM MyTable T2 WHERE T2.[ID] = T1.[ID] 
    ) AS V2 


DROP TABLE #tb 

有人可以建議我如何改善它嗎?

感謝

回答

1

嘗試:

WITH CTE AS 
(
SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) AS 'RowNo', 
ID, Name, Color 
FROM table 
) 
SELECT ID,Name,color 
FROM CTE 
WHERE RowNo = 1 

select 
    * 
from 
(
    Select 
     ID, Name, Color, 
     rank() over (partition by Id order by sum(Name) desc) as Rank 
    from 
     table 
    group by 
     ID 
) 
    HRRanks 
where 
    rank = 1 
+0

我使用的第一示例 - 奇異!!謝謝。 – jose 2010-06-15 19:19:49