如何将 table 列转换为 Sql 服务器 table 中的垂直数据?

How to transform the table columns to vertical data in Sql server tables?

我想将一台 Sql 服务器 table 转换为另一台。

原版table

    Period      Date          Portfolio   Benchmark

    Pre0Month   12/31/2014   -0.0001      -0.0025
    Pre1Month   11/31/2014    0.0122       0.0269
    Pre2Month   10/31/2014    0.0176       0.0244

改造后

    Returns      Pre0Month   Pre1Month    Pre2Month

    Portfolio   -0.0001      0.0122       0.0176
    Benchmark   -0.0025      0.0269       0.0244

因为您使用的是 SQL-Server,所以您可以使用 pivot 命令来执行您想要的操作。在这里查看:https://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx

您也可以使用 DateDiff 函数轻松地按月分隔日期。 https://msdn.microsoft.com/en-us/library/ms189794.aspx

考虑到 table 的名称是 MyTable,您可以按以下方式旋转它:

SELECT * FROM
(
  SELECT Period, [Returns], value
  FROM MyTable
  CROSS APPLY
  (
    SELECT 'Portofolio', CAST(Portofolio as varchar(10)) 
    UNION ALL
    SELECT 'Benchmark', CAST(Benchmark as varchar(10)) 
  ) c([Returns], value)
) d
PIVOT
(
    MAX(value)
    FOR Period IN (Pre0Month, Pre1Month, Pre2Month)
) piv;

这需要 PIVOT 和 UNPIVOT 的组合:

DECLARE @t TABLE(period VARCHAR(32),[date] DATETIME, portfolio DECIMAL(28,4), benchmark DECIMAL(28,4));
INSERT INTO @t(period,[date],portfolio,benchmark)VALUES('Pre0Month','2014-12-31',-0.0001,-0.0025);
INSERT INTO @t(period,[date],portfolio,benchmark)VALUES('Pre1Month','2014-11-30',0.0122,0.0269);
INSERT INTO @t(period,[date],portfolio,benchmark)VALUES('Pre2Month','2014-10-31',0.0176,0.0244);

SELECT
    *
FROM
    (
        SELECT
            *
        FROM
            (
                SELECT
                    period,
                    portfolio,
                    benchmark
                FROM
                    @t
            ) AS t
            UNPIVOT(
                value
                FOR Returns IN (portfolio,benchmark)
            ) AS up
    ) AS t
    PIVOT(
        MAX(value)
        FOR period IN ([Pre0Month],[Pre1Month],[Pre2Month])
    ) AS p;

结果如下:

Returns     Pre0Month   Pre1Month   Pre2Month
benchmark   -0.0025     0.0269      0.0244
portfolio   -0.0001     0.0122      0.0176