0

可能であれば、このクエリについて簡単に質問したいと思います。

以下のような列を持つテーブルがあります。

class_01|class_02|class_03|class_04|class_05|class_06|class_07|class_08|class_09|
Sonto   | Botak  | Semut  | Setting|'<none>'|'<none>'|'<none>'|'<none>'|'<none>'|

次に、where 句を次のように記述します。

SELECT bedrnr 
FROM   bedryf 
WHERE  class_01 IN ('Sonto', 'Botak',  'Semut', 'Setting') 
    OR class_02 IN ('Sonto', 'Botak',  'Semut', 'Setting') 
    OR class_03 IN ('Sonto', 'Botak',  'Semut', 'Setting') 
    OR class_04 IN ('Sonto', 'Botak',  'Semut', 'Setting') 
    OR class_05 IN ('Sonto', 'Botak',  'Semut', 'Setting') 
    OR class_06 IN ('Sonto', 'Botak',  'Semut', 'Setting') 
    OR class_07 IN ('Sonto', 'Botak',  'Semut', 'Setting') 
    OR class_08 IN ('Sonto', 'Botak',  'Semut', 'Setting') 
    OR class_09 IN ('Sonto', 'Botak',  'Semut', 'Setting') 

IN の値が同じ where 句ですが、9 つの異なる列で検索したいだけです。クエリを短くする方法はありますか?

4

2 に答える 2

1
select distinct bedrnr
FROM   bedryf unpivot (value for class in (class_01, class_02, class_03, class_04, class_05, class_06, class_07, class_08, class_09)) b
inner join (
    values ('Sonto'), ('Botak'), ('Semut'), ('Setting') 
) t(thing) on b.value = t.thing

SQL Server 2005:

select distinct bedrnr
FROM   bedryf unpivot (value for class in (class_01, class_02, class_03, class_04, class_05, class_06, class_07, class_08, class_09)) b
inner join (
    select 'Sonto' as thing
    union all 
    select 'Botak' as thing
    union all
    select 'Semut' as thing
    union all
    select 'Setting' as thing
) t(thing) on b.value = t.thing
于 2013-02-18T11:02:01.627 に答える
1

スキーマを修正する必要がありますが、別の方法 (2008 以降の構文)

SELECT bedrnr 
FROM   bedryf
WHERE  EXISTS (SELECT class
               FROM   (VALUES(class_01),
                             (class_02),
                             (class_03),
                             (class_04),
                             (class_05),
                             (class_06),
                             (class_07),
                             (class_08),
                             (class_09)) V(class)
               WHERE  class IN ( 'Sonto', 'Botak', 'Semut', 'Setting' )) 
于 2013-02-18T11:06:11.823 に答える