2010-11-22 77 views
0

請考慮下表:分組數據

alt text

正如你可以看到Name列有一些重複的值與一羣喜歡 我需要有一個查詢,所以我可以取

alt text

請採取考慮到我需要的最快的方法,因爲真正的表是不是這樣的:只是一組像這樣的第一行並且可能有大量數據需要過濾。

在此先感謝。

回答

2

這在很大程度上取決於你如何定義

像這樣「組中的第一個」:

select name, min(code) 
from mytable 
group by name 
order by name 
+0

表現一般。你可能會考慮名稱,代碼列上的索引 – Randy 2010-11-22 23:22:38

0

假設表名是test(其他城市,以匹配你的),試試這個

CREATE TABLE [dbo].[test](
    [name] [varchar](3) NULL, 
    [code] [varchar](5) NULL, 
    [RowNumber] [int] NOT NULL, 
CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED 
(
    [RowNumber] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 


INSERT INTO [test] ([name],[code],[RowNumber])VALUES('A1','AED',1) 
INSERT INTO [test] ([name],[code],[RowNumber])VALUES('A1','BG',2) 
INSERT INTO [test] ([name],[code],[RowNumber])VALUES('A1','WS',3) 
INSERT INTO [test] ([name],[code],[RowNumber])VALUES('A2','CER',4) 
INSERT INTO [test] ([name],[code],[RowNumber])VALUES('A2','HJY',5) 
INSERT INTO [test] ([name],[code],[RowNumber])VALUES('A5','OLP',6) 
INSERT INTO [test] ([name],[code],[RowNumber])VALUES('A6','LOO',7) 
INSERT INTO [test] ([name],[code],[RowNumber])VALUES('A6','AED',8) 

SELECT a.* 
FROM dbo.test a 
     INNER JOIN(SELECT name, 
         MIN(rownumber) AS rownumber 
        FROM dbo.test 
        GROUP BY name) b 
     ON a.name = b.name 
      AND a.rownumber = b.rownumber 
ORDER BY a.name 

如果RowNumber列始終是順序的,則將索引放在該列上。