在SQL Server上,如何将一行多列转换为一行多列?

在SQL Server上,如何将一行多列转换为一行多列?,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有下表: 我需要执行查询以返回以下结果: 我尝试了UNPIVOT,但它不起作用。我有12个月,但举例来说,我只放了2个月 我如何才能做到这一点?您可以使用交叉应用: SELECT tab.sector, sub.* FROM tab CROSS APPLY (VALUES ('Jan', Jan_estimated, Jan_sold), ('Feb', Feb_estimated, Feb_sold) )sub(Month,Val_estim

我有下表:

我需要执行查询以返回以下结果:

我尝试了
UNPIVOT
,但它不起作用。我有12个月,但举例来说,我只放了2个月


我如何才能做到这一点?

您可以使用
交叉应用

SELECT tab.sector, sub.* 
FROM tab
CROSS APPLY (VALUES ('Jan', Jan_estimated, Jan_sold),
                    ('Feb', Feb_estimated, Feb_sold)
  )sub(Month,Val_estimated, Val_sold)

您可以使用
apply

select t.Sector, tt.*
from table t cross apply
     ( values ('Jan', Jan_Estimated, Jan_Sold),
              ('Feb', Feb_Estimated, Feb_Sold),
               . . .
     ) tt (Month, Val_Estimated, Val_Sold);

您可以使用
UNPIVOT

SELECT  sector, [Month] = Substring(col1,1,3), val_Estimated, val_Sold
FROM    ( 
    SELECT * FROM [tableName] 
) as t 
UNPIVOT ( val_Estimated for col1 IN (jan_estimated,feb_estimated)) AS unpvt 
UNPIVOT ( val_Sold for col2 in (jan_sold, feb_sold)) up2
WHERE SUBSTRING(col1,1,3) = SUBSTRING(col2,1,3)