我有一个数据库,需要根据第1列中的值选择不同的列。
如果列1 = 1,则从数据库中选择a,b,c
如果第1列= 2,则从数据库中选择d,e,f
我该怎么办?
答案 0 :(得分:3)
使用union all
:
select a, b, c from table1 where column1 = 1
union all
select d, e, f from table1 where column1 = 2
UNION运算符默认情况下仅选择不同的值。要允许重复值,请使用UNION ALL。
答案 1 :(得分:2)
使用case
:
select (case when col1 = 1 then a else d end),
(case when col1 = 1 then b else e end),
(case when col1 = 1 then c else f end)
from t
where col1 in (1, 2);
注意:这假设列对(a
/ d
等)在类型方面是兼容的。