2010-06-29 11 views
1

첫 번째 첫 번째 열에 동일한 데이터가있는 행만 반환하도록 깔끔한 SQL 쿼리가 있습니까? 돌아왔다? 제가첫 번째 열에서 동일한 데이터가있는 행의 첫 번째 항목 만 선택하는 SQL 쿼리

blah something 
blah somethingelse 
foo blah 
bar blah 
foo hello 

같은 행에있는 경우 즉, 쿼리가 첫 번째 행의 첫 번째 열에서 "ㅋ", "최초로 검출이기 때문에, 세 번째 행은 제이다 (저 제 1, 제 3 및 제 4 행을주지해야한다 첫 번째 열에서 "foo는"및 네 번째 행의 발생은 첫 번째 열에서 "바")의 첫 번째 항목 인 내가 H2 database engine을 사용하고

, 그 중요한 경우

업데이트 :.. 죄송 불분명 한 테이블 정의에 대해서는 여기가 더 좋으며, "blah", "foo"등은 첫 번째 열의 값을 나타냅니다. i n 행.

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

+2

"첫 번째"라고 할 때, "나는 처음으로 우연히 만나다"또는 "첫 번째 알파벳순으로"또는 "첫 번째"의 다른 정의를 의미합니까? :) – Jonathan

+0

@ Jonathon의 질문에 덧붙여 무언가보다 오히려 어쩌면 무엇인가를 선택하는 규칙이 무엇인지 – Mark

답변

1

나는 이것이 당신이 원하는대로한다고 생각하지만 나는 100 % 확실하지 않습니다. 트릭을 할 수

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 
2

분석 요청 : (. 너무 MS SQL 서버 기준)

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 
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; 
관련 문제