使用 SQL 脚本的条件 SQL 查询
Conditional SQL queries with SQL Script
我有两个示例表:
TABLE1:
ID | COLUMN_B| COLUMN_C
_________|_________|_________
1 | 0 | 1
________|_________|_________
2 | 0 | 1
________|_________|_________
3 | 0 | 1
TABLE2:
ID | COLUMN_E| COLUMN_F
________|_________|________
1 | Y | X
________|_________|_________
2 | Y | X
________|_________|_________
3 | Y | X
它们与 ID 列相互关联。我想在 TABLE1 上执行 select,仅当 COLUMN_E 上的值为 Y 时才引入 COLUMN_B 并引入 COLUMN_C。
是否可以创建一个模拟如下内容的条件:
"select column_b, and select column_c IF AND ONLY IF the value on column_e from TABLE2 is Y for the same ID"?
如果我没理解错的话,这只是一个case
表达式:
select t1.column_b,
(case when t2.column_e = 'Y' then t1.column_c end) as column_c
from table1 t1 left join
table2 t2
on t1.id = t2.id;
使用加入
select t1.COLUMN_B,
case when t2.COLUMN_E='Y' then t1.COLUMN_C else null
end as c from table1 t1
left join table2 t2 on t1.id=t2.id
我有两个示例表:
TABLE1:
ID | COLUMN_B| COLUMN_C
_________|_________|_________
1 | 0 | 1
________|_________|_________
2 | 0 | 1
________|_________|_________
3 | 0 | 1
TABLE2:
ID | COLUMN_E| COLUMN_F
________|_________|________
1 | Y | X
________|_________|_________
2 | Y | X
________|_________|_________
3 | Y | X
它们与 ID 列相互关联。我想在 TABLE1 上执行 select,仅当 COLUMN_E 上的值为 Y 时才引入 COLUMN_B 并引入 COLUMN_C。
是否可以创建一个模拟如下内容的条件: "select column_b, and select column_c IF AND ONLY IF the value on column_e from TABLE2 is Y for the same ID"?
如果我没理解错的话,这只是一个case
表达式:
select t1.column_b,
(case when t2.column_e = 'Y' then t1.column_c end) as column_c
from table1 t1 left join
table2 t2
on t1.id = t2.id;
使用加入
select t1.COLUMN_B,
case when t2.COLUMN_E='Y' then t1.COLUMN_C else null
end as c from table1 t1
left join table2 t2 on t1.id=t2.id