IF ELSE的加入条件?

时间:2012-11-06 14:36:38

标签: sql sql-server

我正在使用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

所以,我想在两个表之上加入内部。

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'
  3. 因此on条件存在条件。

    如何编写选择查询?

    修改 我将条件更改为平均年龄,而不是type

3 个答案:

答案 0 :(得分: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 Fiddle Example

<强>输出:

| 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 |

答案 1 :(得分: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'))

答案 2 :(得分:0)

一种方法是使用一个表来映射两种类型的类型:

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

然后你可以将这个表内连接到另外两个。

相关问题