3

私はこの種のテーブルを持っています:

a   b

8   7
8   2
9   7
9   2
9   3

「b」の正確な検索値を持つように「a」値を取得したい。たとえば、(7,2) を検索する場合はクエリで 8 を返し、(7,2,3) を検索する場合は 9 を返し、それ以外の場合は Null を返す必要があります。

Search      Result
(7,2)       8
(7,2,3)     9
(7,3)       Null
(7,2,4)     Null
...

「group by」連結を使用せずにそれを行うことは可能ですか?

[編集] 「連結によるグループ化」とは、MySql の GROUP_CONCAT() のようなもの、または任意の文字列関数を意味します。

4

4 に答える 4

0

「連結によるグループ化」の意味がわからない-なしでは実行できないと思いますgroup by:

DBMS を指定しなかったため、これは ANSI SQL です。

with search_values (val) as (
   values (7), (2)
)
-- first part gets all those that do have the search values
-- but will also include those rows that have more than the searched ones
select a
from data
where b in (select val from search_values)
group by a
having count(distinct b) = (select count(*) from search_values)

intersect
-- the intersect then filters out those that have exactly the search values

select a
from data
group by a
having count(distinct b) = (select count(*) from search_values);

SQLFiddle の例: http://sqlfiddle.com/#!15/dae93/1

「検索値」に CTE を使用すると、それらの繰り返しが回避され、検索対象のアイテム数の「ハードコーディング」が回避されます。7,2,3 を探す場合は、CTE に別の値を追加するだけです

使用する代わりに、intersect相互に関連するサブクエリで書き換えることができます

with search_values (val) as (
   values (7), (2)
)
select d1.a
from data d1
where d1.b in (select val from search_values)
group by d1.a
having count(distinct d1.b) = (select count(*) from search_values)
   and count(distinct d1.b) = (select count(*) from data d2 where d2.a = d1.a);
于 2014-03-27T11:29:53.153 に答える