2013-06-12 29 views
0

我使用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

看起来你实际上想要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 | 
+0

完美,谢谢 – user1706426