反向透视查询中的帮助

时间:2011-09-20 04:59:07

标签: sql-server

我不知道我将如何做到这一点。 简单的例子

studentid    |   sub1id     | sub2id    | and so on.....
----------------------------------------------------------
1            |     1        |   2       | and so on
3            |     5        |   6       | and so on

使用这样的表结构......我希望以下形式输出特定学生

学生1

student    |  sub   |
======================
1          |   1    |
1          |   2    |

学生2

student    |  sub   |
======================
2          |   5    |
2          |   6    |

1 个答案:

答案 0 :(得分:1)

declare @T table
(
  studentid int,
  sub1id int,
  sub2id int
)
insert into @T values
(1, 1, 2),
(3, 5, 6)

select studentid, sub
from (select studentid, sub1id, sub2id
      from @T
      where studentid = 3) as T
unpivot (sub for C in (sub1id, sub2id)) as U