2012-04-09 8 views
0

Oracleのバージョンは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 

このクエリの結果は、例えば、

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

結果は何とか1、 で、= 1 テイクt1.t_id非常に奇妙である

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

、あります'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 

なぜですか?

答えて

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. 
+0

私はちょうどスカラサブクエリが「でグループ」を持っている、と私は理由を知りたい興味深い事実を見つけ、スカラー副問合せを使用したくありません。この質問文字列が私のオラクルで働いたのは不思議です。 – user1021531

関連する問題