这是我当前的数据集:
rname ename
Advises Grad_student
Advises Faculty
Chairs Department
Chairs Faculty
我正在尝试将其转换为这种格式:
rname ename1 ename2
advises grad_student faculty
chairs department faculty
这是我迄今为止尝试过的:
select distinct
r1.rname, r1.ENAME as ename1,r2.ENAME as ename2
from [dbo].[RELATIONSHIPS] r1
inner join(
select distinct
RNAME, ENAME
from [dbo].[RELATIONSHIPS]) r2
on r1.RNAME = r2.RNAME
where r1.ENAME <> r2.ENAME
order by r1.rname
这是我得到的回复:
rname ename1 ename2
Advises Grad_student Faculty
Advises Faculty Grad_student
Chairs Department Faculty
Chairs Faculty Department
我该如何修复我的代码才能只返回 1 行?
最佳答案
您可以将row_number()
与条件聚合
结合使用:
with cte as (
select rname, ename, row_number() over (partition by rname order by ename) rn
from relationships
)
select rname,
max(case when rn = 1 then ename end) ename1,
max(case when rn = 2 then ename end) ename2
from cte
group by rname
关于sql - 如何在sql中旋转第二列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30134347/