2012-11-06 58 views
6

子句子查詢語句比方說,我有這樣的查詢:凡在選擇

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

我想篩選就成爲「記錄」列不爲空。

我不能做到這一點:

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

,我想出了是寫這個結果集的表值參數,並且對結果集是一個單獨的查詢最好。有任何想法嗎?

+0

@RichardTheKiwi您的查詢是完美的,但我編輯它做得更短。選擇X. * from(選擇col1,col2,(select ..... from table2)作爲table1)中的記錄X其中記錄不爲空; –

回答

9

只要將它移動到一個派生查詢。您不能使用WHERE子句中SELECT子句中定義的列。

Select col1, col2, records 
from 
(
    Select col1, 
      col2, 
      (select ..... from table2) as records 
    from table1 
) X 
where records is not null; 
3

你應該做一些小的修改有:

首先,在子查詢中添加TOP子句強制查詢只返回一個表2的記錄。像這樣的子查詢應該只返回一個標量值。

其次,子查詢的列列表中只能有一列,所以返回值應該是一個標量。

最後,您不能過濾select子句中的子查詢或任何生成的列。所以我的建議是使用"join""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 
     ) 

乾杯

+0

它說Where Where clause – user194076

+0

「無效的列名記錄」我先生道歉。再次查看更新的帖子。謝謝。 – Rikki