我有一个包含不同列的表,我需要根据特定列的值显示不同的列。
我的桌子是这样的:
select col1, col2, col3, col4, col5, col6
from table1
所以,举个例子:
如果col1 = '1‘-->显示col3和col4。
如果col2 = '1‘-->显示col5和col6
发布于 2016-05-20 10:06:27
使用case
表达式选择要返回的列。请注意,案例的返回类型必须兼容,即col3和col5,以及col4和col6。
select case when col1 = 1 then col3
when col2 = 1 then col5
end,
case when col1 = 1 then col4
when col2 = 1 then col6
end
from tablename
或者,做一个UNION ALL
select col3, col4
from tablename where col1 = 1
union all
select col5, col6
from tablename where col2 = 1
剩下的问题-如果col1和col2都是1怎么办?或者如果他们都不是?
发布于 2016-05-20 10:33:08
经验法则1:将用于过滤的列返回给调用者。
经验法则2:不要使用union all
,它会返回重复的结果,你的结果不会是一个“关系”(虽然在这种情况下不会有重复,因为col1是一个键,但我仍然认为union
是最好的意图)。
select col1, col2, col3 AS colum_a, col4 AS colum_b
from table1
where col1 = 1
union
select col1, col2, col5 AS colum_a, col6 AS colum_b
from table1
where col2 = 1;
https://stackoverflow.com/questions/37343769
复制