SELECT column_a1,column_b1,column_c1,column_d1,column_e1,column_f1,column_g1
FROM mytable WHERE id=12 AND detectcolumn=1
UNION ALL
SELECT column_a2,column_b2,column_c2,column_d2,column_e2,column_f2
FROM mytable WHERE id=12 AND detectcolumn=2
UNION ALL
SELECT column_a3,column_b3,column_c3,column_d3,column_e3,column_f3,column_g3
FROM mytable WHERE id=12 AND detectcolumn=3
UNION ALL
SELECT column_a4 from mytable WHERE id=12 AND detectcolumn=4
UNION ALL
SELECT column_a5 from mytable WHERE id=12 AND detectcolumn=5
UNION ALL
SELECT column_a6 from mytable WHERE id=12 AND detectcolumn=6
UNION ALL
SELECT column_a7 from mytable WHERE id=12 AND detectcolumn=7
如何将所有这些sql语句组合成一个单独的sql语句。我希望根据detectcolumn的值从mytable中获取特定列。
我尝试使用UNION ALL,但它出错 ORA-01789:查询块的结果列数不正确
答案 0 :(得分:2)
使用如下模式:
select
case detectcolumn
when 4 then column_a4
when 5 then column_a5
when 6 then column_a6
end
from
my_table
where
id = 12 and
detectcolumn in (4,5,6)