且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从多列中选择值到单列

更新时间:2022-12-12 10:54:30

可以使用UNPIVOT函数得到最终结果:

You can use the UNPIVOT function to get the final result:

select value
from yourtable
unpivot
(
  value
  for col in (I1, I2, I3)
) un
order by id, col;

由于您使用的是 SQL Server 2008+,那么您还可以使用带有 VALUES 子句的 CROSS APPLY 来取消旋转列:

Since you are using SQL Server 2008+, then you can also use CROSS APPLY with the VALUES clause to unpivot the columns:

select value
from yourtable
cross apply
(
    values
        ('I1', I1),
        ('I2', I2),
        ('I3', I3)
) c(col, value)
where value is not null
order by id, col