这是我当前的数据集:
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行?
答案 0 :(得分:1)
您可以将row_number()
与conditional aggregation
:
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
答案 1 :(得分:1)
在oracle中
select * from
(select rname,ename,
RANK() over (partition by rname order by ename) Id
FROM relationships)
PIVOT(MAX(ename) for Id in (1 as ename1, 2 as ename2))
答案 2 :(得分:0)
如果只有两个,那就这样做吧。简短又甜蜜。
rescue Stripe::CardError => e
error = e.message
Rails.logger.error "Stripe card error for account #{@account}, error #{e}"