If the order does not really matter (as you say in your comment) then you can do it with ROW_NUMBER()
window function:
(如果顺序并不重要(如您在评论中所述),则可以使用ROW_NUMBER()
窗口函数进行操作:)
with cte as (
select *,
row_number() over (partition by [Department] order by [Jan]) rn1,
row_number() over (partition by [Department] order by [Feb]) rn2,
row_number() over (partition by [Department] order by [Mar]) rn3,
row_number() over (partition by [Department] order by [Apr]) rn4
from tablename
)
select c1.[Department], c1.[Jan], c2.[Feb], c3.[Mar], c4.[Apr]
from cte c1
inner join cte c2 on c2.[Department] = c1.[Department] and c2.rn2 = c1.rn1
inner join cte c3 on c3.[Department] = c1.[Department] and c3.rn3 = c1.rn1
inner join cte c4 on c4.[Department] = c1.[Department] and c4.rn4 = c1.rn1
where coalesce(c1.[Jan], c2.[Feb], c3.[Mar], c4.[Apr]) is not null
order by c1.[Department], c1.[Jan] desc, c2.[Feb] desc, c3.[Mar] desc, c4.[Apr] desc
See the demo .
(参见演示 。)
Results:
(结果:)
> Department | Jan | Feb | Mar | Apr
> :--------- | ---: | ---: | --: | ---:
> A | 1 | null | 2 | 7
> B | 1 | 6 | 5 | null
> B | null | null | 2 | null
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…