如何将具有任何列的值 Table 复制到具有一列的其他表

How to copy values Table with any columns to other tables with one columns

我想将一个 table 的列复制到另一个 table 的列中。

我的主要table - TBL_Sku2:

 id       sku1                     sku2                sku3                 sku4            sku5       
 ---     -----------       -----------------    -------------------  -----------------     ---------
 1   1GBDDR3-1066-21       2GBDDR3-1066-21        4GBDDR3-1066-414          Null               Null
 2   512MBDDR2-533-1038           null              null                     null            null
 3   1GBDDR2-533-1068        512MBDDR2-533-1033       Null                 Null                    Null

输出应该是这样的:

TBL_SKU_F1 的副本:

      Id                      sku                          
    -----------       ----------------- 
       1                1GBDDR3-1066
       2                2GBDDR3-1066
       3                4GBDDR3-1066
       4                512MBDDR2-533
       5                1GBDDR2-533
       6                512MBDDR2-533

我目前的尝试:

select 
    [SKU1], [SKU2], [SKU3],
    [SKU4], [SKU5], [SKU6]
from
    [dbo].[TBL_Sku2]
unpivot 
    (Sku for col_name in ([SKU1], [SKU2], [SKU3], [SKU4], [SKU5], [SKU6]));

查询尝试#2:

select 
    [SKU1], [SKU2], [SKU3], [SKU4], [SKU5], [SKU6]
from
    [dbo].[TBL_Sku2]
cross apply
    (values('SKU1', [SKU1]), ('SKU2', [SKU2]), ('SKU3', SKU3),
           ('SKU4', SKU4), ('SKU5', SKU5), ('SKU6', SKU6)) c(col, value)
where 
    value is not null

我无法将这些列插入或转换为一列...

您在尝试 1 中非常接近:

     SELECT row_number() over (order by (select null)) as id, u.sku
     FROM [dbo].[TBL_Sku2]
     UNPIVOT (
        Sku 
        FOR SkuName IN (
            [SKU1]
          ,[SKU2]
          ,[SKU3]
          ,[SKU4]
          ,[SKU5]
          ,[SKU6]
)) AS  u;

现在可以正常化了!

select row_number() over( order by (select null)) as id,
b.* from #temp t
cross apply
(
values(sku1),
      (sku2),
      (sku3),
      (sku4),
      (sku5)
) b(final)
where final is not null