0

私のオラクルのバージョンは10.2です。スカラーサブクエリに集計演算がある場合、それは非常に奇妙です。t_testという名前のテーブルは次のようになりました。

t_id    t_name
 1       1
 2       1
 3       2
 4       2
 5       3
 6       3      

クエリ文字列は次のようになりました。

select t1.t_id,
       (select count(t_name)
         from (select t2.t_name 
                 from t_test t2 
                 where t2.t_id=t1.t_id 
                 group by t2.t_name)) a
from t_test t1

このクエリの結果は、

t_id  a
 1    3
 2    3
 3    3
 4    3
 5    3
 6    3

これは非常に奇妙です。たとえば、t1.t_id=1とします。

select count(t_name)
 from (select t2.t_name 
         from t_test t2 
         where t2.t_id=1
         group by t2.t_name)

結果は1で、どういうわけか、「where」演算子は機能しません。結果は、次のようにクエリを配置した場合とまったく同じです。

select t1.t_id,
       (select count(t_name)
         from (select t2.t_name 
                 from t_test t2 
                 group by t2.t_name)) a
from t_test t1

なぜ?

4

1 に答える 1

0

実行しているクエリを正確に示すSQL*Plusからのカットアンドペーストを投稿できますか?投稿したクエリは有効ではないようです。エイリアスt1は、参照しているサブクエリでは有効になりません。そのため、ここに投稿する問題を単純化しているのではないかと思いますが、誤って重要なものを省略してしまいました。

SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select 1 id, 1 name from dual union all
  3    select 2,1 from dual union all
  4    select 3,2 from dual union all
  5    select 4,2 from dual union all
  6    select 5,3 from dual union all
  7    select 6,3 from dual
  8  )
  9  select t1.id
 10        ,(select count(b.name)
 11            from (select t2.name
 12                    from x t2
 13                   where t2.id = t1.id
 14                   group by t2.name) b) a
 15*   from x t1
SQL> /
                 where t2.id = t1.id
                               *
ERROR at line 13:
ORA-00904: "T1"."ID": invalid identifier

おそらく、このようなクエリを作成する方がはるかに自然です(実際にスカラーサブクエリを使用したい場合)。ここt1で、スカラーサブクエリの有効なエイリアスになります。

SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select 1 id, 1 name from dual union all
  3    select 2,1 from dual union all
  4    select 3,2 from dual union all
  5    select 4,2 from dual union all
  6    select 5,3 from dual union all
  7    select 6,3 from dual
  8  )
  9  select t1.id
 10        ,(select count(t2.name)
 11            from x t2
 12           where t2.id = t1.id) cnt
 13*   from x t1
SQL> /

        ID        CNT
---------- ----------
         1          1
         2          1
         3          1
         4          1
         5          1
         6          1

6 rows selected.
于 2012-04-09T14:31:16.097 に答える