看起來你實際上想要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 with Demo
兩個查詢得到的結果:
| COL | VALUE | SPONSORID |
-------------------------------
| allow_r | 1 | 2 |
| allow_h | 1 | 2 |
完美,謝謝 – user1706426