2017-05-18 13 views
0

where if節内に 'if else'条件を追加しようとしていますが、どうすればよいかわかりません。下の表のセットを見ると、クエリでProduct Lineのすべてのサブタイプが抽出され、[Product Line Subtype] = 'Marine' =の場合にのみ条件を追加するように、結果をフィルタリングしようとしています。それが海洋である場合、セクション利益コードの2つの組み合わせだけを考慮し、他の組み合わせは除外する必要があります。製品版のラインのサブタイプ=海洋その後、節=内陸と利益コードビルダーwhere節内の条件

組み合わせ2のProdラインのサブタイプ=海洋その後、節=海と利益コード=株式に

を=

コンビネーション1私の実際のテーブルには、Prod line Subtype = Marineの場合、以下の表に示すよりも大きな組み合わせがありますが、上記の2つの組み合わせだけを結果セットにフィルタリングしたいだけです。どんな助けでも大歓迎です!

メインテーブル

+--+------------------+-------------+-----------------+ 
| |Prod line Subtype | Section  | Profit Code | 
+--+------------------+-------------+-----------------+ 
| | Marine   | Inland  | Builders  | 
| | Marine   | Ocean  | Stock   | 
| | Property   | General  | Transport  | 
| | Energy   | Source  | Others   | 
| | Property   | General  | Transport  | 
| | Energy   | Source  | Transport  | 
| | Marine   | Inland  | Transport  |  
| | Marine   | Floaters | Transport  |  
| | Marine   | Cargo  | Others   |  
+--+------------------+-------------+---------------- + 

期待される成果

+--+------------------+-------------+-----------------+ 
| |Prod line Subtype | Section  | Profit Code | 
+--+------------------+-------------+-----------------+ 
| | Marine   | Inland  | Builders  | 
| | Marine   | Ocean  | Stock   | 
| | Property   | General  | Transport  | 
| | Energy   | Source  | Others   | 
| | Property   | General  | Transport  | 
| | Energy   | Source  | Transport  | 
+--+------------------+-------------+---------------- + 

マイクエリーの試み:

select * 
from #Step1 
where c1.row_ord = 1 
and c1.[Prod Line Subtype] = 'Marine' AND (
    (c1.[Section] = 'Inland' AND c1.[Profit Code] = 'Builder') 
    OR (c1.[Section] = 'Ocean' AND c1.[Profit Code] = 'Stock') 
) 
+0

から、あるいは条件[製品版ラインサブタイプ] =「海洋」を省略することができ、あなたの現在のクエリは何ですか? –

+1

'WHERE'節で' case' _expressions_の代わりに 'AND' /' OR'を使用する方が一般に良いでしょう。 – jarlh

+0

[SQL Serverの条件付きWHERE句]の重複している可能性があります(http://stackoverflow.com/questions/18629132/conditional-where-clause-in-sql-server) –

答えて

1

何について:

Select * from [Your table] 
    Where ([Prod line Subtype]<>'Marine' Or 
     (Section='Inland' And [Profit Code]='Builders') Or 
     (Section='Ocean' And [Profit Code]='Stocks')  
    ) 

あなたはこのためにcase文を使用することができます

+0

ありがとうございました。 – Joe