13

次のようなクエリがあるとします。

   Select col1, 
          col2, 
          (select count(smthng) from table2) as 'records'
   from table1

「レコード」列でnullにならないようにフィルタリングしたい。

これはできない:

         Select col1, 
                col2, 
               (select count(smthng) from table2) as 'records'
          from table1
        where records is not null  

私が思いついた最善の方法は、この結果セットをテーブル値パラメーターに書き込み、その結果セットに対して別のクエリを作成することです。何か案は?

4

2 に答える 2

18

派生クエリに移動するだけです。SELECT 句で定義された列を WHERE 句で使用することはできません。

Select col1, col2, records
from
(
    Select col1, 
           col2, 
           (select ..... from table2) as records
    from table1
) X
where records is not null;
于 2012-11-06T23:45:22.020 に答える
3

そこで少し変更を加える必要があります。

まず、サブクエリにTOP句を追加して、クエリがそのテーブルの1つのレコードのみを返すようにします2。このようなサブクエリは、スカラー値のみを返す必要があります。

次に、サブクエリはその列リストに1つの列しか含めることができないため、戻り値はスカラーでなければなりません。

最後に、select句でサブクエリまたは作成された列をフィルタリングすることはできません。したがって、"join"sまたはを使用することをお勧めします"exists"

Select col1, 
       col2
       from table1
       left outer join
            table2
       on table1.key = table2.key
       where not table2.key is null

またはこれ:

Select col1, 
       col2
       from table1
       inner join
            table2
       on table1.key = table2.key

またはこれ:

Select col1, 
       col2
       from table1
       where exists (
            select *
                  from table2
                  where table2.key = table1.key
                  and   not table2.somethingelse is null
                  -- or any other relevant conditions
       )

乾杯

于 2012-11-06T23:41:59.230 に答える