1

最初の列に同じデータを持つ最初の行のみが返されるように、行を返す適切な SQL クエリはありますか? つまり、次のような行がある場合

blah something
blah somethingelse
foo blah
bar blah
foo hello

クエリは、1 行目、3 行目、4 行目を表示する必要があります (最初の行は最初の列で "blah" が最初に出現するため)、3 行目は最初の列で "foo" が最初に出現する行であり、4 行目は最初の列の最初の「バー」)。

それが問題なら、私はH2データベースエンジンを使用しています。

更新:テーブルの定義が不明確で申し訳ありません。「何とか」、「foo」などは、行の最初の列の値を示します。

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

4 に答える 4

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
于 2010-06-29T08:54:42.690 に答える
2

分析リクエストはそのトリックを行うことができます。

Select *
from (
    Select rank(c1) over (partition by c1) as myRank, t.*
    from myTable t )
where myRank = 1

ただし、これは V1.3.X の優先順位 2 にすぎません。

http://www.h2database.com/html/roadmap.html?highlight=RANK&search=rank#firstFound

于 2010-06-29T09:17:32.923 に答える
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
于 2010-06-29T08:46:49.227 に答える
1

可能な限り高速なクエリに関心がある場合: テーブルの最初の列にインデックスを設定することは比較的重要です。そうすれば、クエリ プロセッサはそのインデックスから値をスキャンできます。次に、おそらく最速の解決策は、「外部」クエリを使用して個別の c1 値を取得し、さらに「内部」クエリまたはネストされたクエリを使用して、2 番目の列の可能な値の 1 つを取得することです。

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;
于 2010-07-03T16:44:00.010 に答える