with T1 (职务, id) as ( select '班长', 4 union all select '学习委员', 2 union all select '文娱委员', 3 union all select '体育委员', 5 ), T2 (id, 姓名, 年龄, 性别, 爱好) as ( select 1, '关羽', 10, '男', null union all select 2, '诸葛亮', 10, '男', null union all select 3, '貂蝉', 10, '女', null union all select 4, '刘备', 10, '男', null union all select 5, '张飞', 10, '男', null )/* 行转列 */ select 班长 = max(case when 职务='班长' then T2.姓名 end) , 学习委员 = max(case when 职务='学习委员' then T2.姓名 end) , 文娱委员 = max(case when 职务='文娱委员' then T2.姓名 end) , 体育委员 = max(case when 职务='体育委员' then T2.姓名 end) from T1 inner join T2 on T1.id = T2.id
with T1 (职务, id) as
(
select '班长', 4 union all
select '学习委员', 2 union all
select '文娱委员', 3 union all
select '体育委员', 5
), T2 (id, 姓名, 年龄, 性别, 爱好) as
(
select 1, '关羽', 10, '男', null union all
select 2, '诸葛亮', 10, '男', null union all
select 3, '貂蝉', 10, '女', null union all
select 4, '刘备', 10, '男', null union all
select 5, '张飞', 10, '男', null
)/* 行转列 */
select 班长 = max(case when 职务='班长' then T2.姓名 end)
, 学习委员 = max(case when 职务='学习委员' then T2.姓名 end)
, 文娱委员 = max(case when 职务='文娱委员' then T2.姓名 end)
, 体育委员 = max(case when 职务='体育委员' then T2.姓名 end)
from T1 inner join
T2 on T1.id = T2.id