且构网

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

如何将列转置为 sql server 中的行

更新时间:2023-11-18 22:52:22

有几种不同的方法可以获得您想要的结果.

There are a few different ways that you can get the result that you want.

您可以将 SELECTUNION ALL 一起使用:

You can use a SELECT with UNION ALL:

select store, '1/1/2013' date, [1/1/2013] value
from yourtable
union all
select store, '2/1/2013' date, [2/1/2013] value
from yourtable;

参见SQL Fiddle with Demo.

您可以使用 UNPIVOT 函数:

You can use the UNPIVOT function:

select store, date, value
from yourtable
unpivot
(
  value
  for date in ([1/1/2013], [2/1/2013])
) un;

参见 SQL Fiddle with Demo.

最后,根据您的 SQL Server 版本,您可以使用 CROSS APPLY:

Finally, depending on your version of SQL Server you can use CROSS APPLY:

select store, date, value
from yourtable
cross apply
(
  values
    ('1/1/2013', [1/1/2013]),
    ('2/1/2013', [2/1/2013])
) c (date, value)

请参阅SQL Fiddle with Demo.所有版本都会给出以下结果:

See SQL Fiddle with Demo. All versions will give a result of:

|   STORE |     DATE | VALUE |
|---------|----------|-------|
| XYZ INC | 1/1/2013 |  1000 |
| XYZ INC | 2/1/2013 |  2000 |