我一直在尝试根据条件和值打印列名。
我的问题是这个
如果两行中的所有列(如数据x和y)都具有值yes
,那么它应该打印那些列名,否则不会
我的代码:
select 'A' from world.city where A = 'yes' AND data=y and data=x union all
select 'B' from world.city where B= 'yes' AND data=y and data=x union all
select 'C' from world.city where C= 'yes' AND data=y and data=x union all
select 'D' from world.city where D= 'yes' AND data=y and data=x union all
select 'E' from world.city where E= 'yes' AND data=y and data=x;
它没有给出完美的结果。
答案 0 :(得分:1)
做一个sum和union all然后用sum('yes')过滤行等于2.见下文。
select colname
from (
select 'A' as colname,sum(case when A='yes' then 1 else 0 end) col
from tbl where data in ('X','Y')
union all
select 'B',sum(case when B='yes' then 1 else 0 end)
from tbl where data in ('X','Y')
union all
select 'C',sum(case when C='yes' then 1 else 0 end)
from tbl where data in ('X','Y')
union all
select 'D',sum(case when D='yes' then 1 else 0 end)
from tbl where data in ('X','Y')
union all
select 'E',sum(case when E='yes' then 1 else 0 end)
from tbl where data in ('X','Y')) tab
where col = 2;
Result:
colname
B
D