2

SQL Server を使用しています。

item_table次のようなテーブルがあります。

item   age
--------------    
1      1 
1      6 
2      2    

私はこのような他のテーブルを持っていますprice_table:

item    pricetype    price
--------------------------    
1       O             5
1       P             6
1       V             7
2       O             8
2       P             9
2       V             10

だから、私は2つのテーブルの上に内部結合したい.

select *
from item_table i
inner join price_table p
on ...

については、次の条件がありますon

  1. アイテムの平均年齢が より大きい場合、次の3ようにします。inner join price_table on pricetype = 'O' or pricetype = 'P'
  2. そうでない場合は、次のことを行います。inner join price_table on pricetype = 'O' or pricetype = 'P' or pricetype = 'V'

だから条件には条件がありonます。

選択クエリを作成するにはどうすればよいですか?

編集: 条件を平均年齢に変更しましたが、代わりにtype

4

3 に答える 3

7
select i.item, i.type, p.pricetype, p.price
from item_table i
inner join price_table p on i.item = p.item 
    and (i.type = 1 and p.pricetype in ('O', 'P'))
        or (i.type = 2 and p.pricetype in ('O', 'P', 'V'))

SQL フィドルの例

出力:

| ITEM | TYPE | PRICETYPE | PRICE |
-----------------------------------
|    1 |    1 |         O |     5 |
|    1 |    1 |         P |     6 |
|    2 |    2 |         O |     5 |
|    2 |    2 |         P |     6 |
|    2 |    2 |         V |     7 |
|    2 |    2 |         O |     8 |
|    2 |    2 |         P |     9 |
|    2 |    2 |         V |    10 |
于 2012-11-06T14:38:26.747 に答える
0

1 つのアプローチは、2 つの型の間をマッピングするテーブルを作成することです。

itemtype    pricetype
---------------------
1           O
1           P
2           O
2           P
2           V

次に、このテーブルを他の 2 つに内部結合できます。

于 2012-11-06T14:58:46.397 に答える
0

where私はそれを次のように句に入れます。

select *
from item_table i
inner join price_table p on 
i.item = p.item
where
(pricetype in ('O', 'P'))
    or (type = 2 and pricetype in ('V'))
于 2012-11-06T14:49:22.967 に答える