Sql 如何在查询中取消PIVOT结果?

Sql 如何在查询中取消PIVOT结果?,sql,sql-server,unpivot,Sql,Sql Server,Unpivot,我正在使用MS SQL 2005 以下是查询: SELECT allow_r, allow_h, allow_c, sponsorid FROM Sponsor WHERE sponsorid = 2 结果是: allow_r allow_h allow_c sponsorid ---------- ---------- ---------- ----------- 1 1 0 2 我需要它是: allow_r 1

我正在使用MS SQL 2005

以下是查询:

SELECT allow_r, allow_h, allow_c, sponsorid
FROM Sponsor 
WHERE sponsorid = 2
结果是:

allow_r   allow_h     allow_c    sponsorid
---------- ---------- ---------- -----------
1          1          0          2
我需要它是:

allow_r   1    2
allow_h   1    2

allow_c不应出现在结果中,因为它的值为0。看起来您实际上想要将列转换为行的数据。您可以使用以下选项:

select col, value, sponsorid
from sponsor
unpivot
(
  value
  for col in (allow_r, allow_h, allow_c)
) unpiv
where sponsorid = 2
  and value <> 0
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;
|     COL | VALUE | SPONSORID |
-------------------------------
| allow_r |     1 |         2 |
| allow_h |     1 |         2 |