user1706426
user1706426

Reputation: 417

How to unpivot result in query?

I am using MS SQL 2005.

This is the query:

SELECT allow_r, allow_h, allow_c, sponsorid
FROM Sponsor 
WHERE sponsorid = 2

This is the result:

allow_r   allow_h     allow_c    sponsorid
---------- ---------- ---------- -----------
1          1          0          2

I need it to be:

allow_r   1    2
allow_h   1    2

allow_c should not be in the result as its 0

Upvotes: 0

Views: 58

Answers (1)

Taryn
Taryn

Reputation: 247700

It seems like you actually want to UNPIVOT the data which turns the columns into rows. You can use the following:

select col, value, sponsorid
from sponsor
unpivot
(
  value
  for col in (allow_r, allow_h, allow_c)
) unpiv
where sponsorid = 2
  and value <> 0

See SQL Fiddle with Demo.

The UNPIVOT function does the same thing as using a UNION ALL query:

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;

See SQL Fiddle with Demo

Both queries give a result:

|     COL | VALUE | SPONSORID |
-------------------------------
| allow_r |     1 |         2 |
| allow_h |     1 |         2 |

Upvotes: 1

Related Questions