似乎您实际上想要UNPIVOT将列转换为行的数据。您可以使用以下内容:
select col, value, sponsorid
from sponsor
unpivot
(
value
for col in (allow_r, allow_h, allow_c)
) unpiv
where sponsorid = 2
and value <> 0
请参阅SQL Fiddle with Demo。
UNPIVOT 函数的作用与使用 UNION ALL 查询相同:
select 'allow_r' as col, allow_r as value, sponsorid
from sponsor
where sponsorid = 2
and allow_r <> 0
union all
select 'allow_h' as col, allow_h as value, sponsorid
from sponsor
where sponsorid = 2
and allow_h <> 0
union all
select 'allow_c' as col, allow_c as value, sponsorid
from sponsor
where sponsorid = 2
and allow_c <> 0;
请参阅带有演示的 SQL Fiddle
两个查询都给出了结果:
| COL | VALUE | SPONSORID |
-------------------------------
| allow_r | 1 | 2 |
| allow_h | 1 | 2 |