2013-06-12 30 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