2010-06-29 75 views
1

是否存在將返回行的整齊SQL查詢,以致只有第一個行的發生在第一列中具有相同數據回?也就是說,如果我有一個像用於僅選擇在第一列中具有相同數據的行的第一次出現的SQL查詢

blah something 
blah somethingelse 
foo blah 
bar blah 
foo hello 

行查詢應該給我的第一,第三和第四行(由於第一行是第一列「嗒嗒」」第一次出現,第三行是第一在第一列「富」,和第四排的發生是在第一列「巴」)的第一次出現

我使用H2 database engine,如果該事項

更新:。對不起關於不明確的表定義,這裏更好;「blah」,「foo」等表示第一列的值在行中。

blah [rest of columns of first row] 
blah [rest of columns of second row] 
foo [-""- third row] 
bar [-""- fourth row] 
foo [-""- fifth row] 
+0

請問你表有一個PK列? – codingbadger 2010-06-29 08:41:15

+2

當你說「第一」時,你的意思是「我偶然發現的第一個」還是「第一個按字母順序排列」,或者是「第一個」的其他定義? :) – Jonathan 2010-06-29 08:41:41

+0

在@ Jonathon的問題中增加了什麼規則來選擇什麼東西而不是blah somethingelse – Mark 2010-06-29 08:51:46

回答

1

我認爲這是做你想做的,但我不是100%確定。 (MS SQL Server上基於太)

create table #t 
(
PKCol int identity(1,1), 
Col1 varchar(200) 
) 

Insert Into #t 
Values ('blah something') 
Insert Into #t 
Values ('blah something else') 
Insert Into #t 
Values ('foo blah') 
Insert Into #t 
Values ('bar blah') 
Insert Into #t 
Values ('foo hello') 


Select t.* 
From #t t 
Join (
    Select min(PKCol) as 'IDToSelect' 
    From #t 
    Group By Left(Col1, CharIndex(space(1), col1)) 
)q on t.PKCol = q.IDToSelect 

drop table #t 
3

如果第2欄按字母順序排列的意思,這裏是一些SQL來獲得這些行:

create table #tmp (
    c1 char(20), 
    c2 char(20) 
) 
insert #tmp values ('blah','something') 
insert #tmp values ('blah','somethingelse') 
insert #tmp values ('foo','ahhhh') 
insert #tmp values ('foo','blah') 
insert #tmp values ('bar','blah') 
insert #tmp values ('foo','hello') 

select c1, min(c2) c2 from #tmp 
group by c1 
1

如果你有興趣在最快的查詢:這是比較重要的是對第一索引表的列。這樣查詢處理器就可以掃描該索引的值。然後,最快的解決辦法可能是使用一個「外」的查詢來獲得不同的C1值,再加上一個「內部」或嵌套查詢來獲取第二列的可能值之一:

drop table test; 
create table test(c1 char(20), c2 char(20)); 
create index idx_c1 on test(c1); 

-- insert some data (H2 specific) 
insert into test select 'bl' || (x/1000), x from system_range(1, 100000); 

-- the fastest query (64 ms) 
select c1, (select i.c2 from test i where i.c1=o.c1 limit 1) from test o group by c1; 

-- the shortest query (385 ms) 
select c1, min(c2) c2 from test group by c1; 
相關問題