如何在查询中取消结果?

时间:2013-06-12 13:49:35

标签: 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    2
allow_h   1    2

allow_c不应该在结果中作为0

1 个答案:

答案 0 :(得分:1)

您似乎确实想要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 |