无法在sql中交换行

时间:2018-01-22 06:53:03

标签: sql sql-server inner-join

我有下表,首先插入名称。然后我会得到我需要用名字映射的ID

     ID  NAME
    null   Test1
    null    Test2
    1      null
    2      null

here

我需要像

这样的结果
ID  NAME
1    Test1
2    Test2

我尝试了下面的查询,但它对我不起作用

select t1.ID , t2.Name from table1 T1 join table1 t2 on T1.id = t2.id

1 个答案:

答案 0 :(得分:0)

根据屏幕简介,您正在使用SQL Server,您可以尝试double表达式,这可能对您有所帮助

cte

结果:

;with cte as
(
    select max(id) id, row_number() over (order by (select 1)) rn from
    ( 
       select *, rank() over(order by id) rnk from table
    ) a
    group by a.rnk 
    having max(id) is not null
), cte1 as
(
    select max(name) name, row_number() over (order by (select 1)) rn from
    ( 
       select *, rank() over(order by name) rnk from table
    ) a
    group by a.rnk 
    having max(name) is not null
)
select c.id, c1.name from cte c
join cte1 c1 on c1.rn = c.rn