简体   繁体   English

如何将表列转换为Sql server表中的垂直数据?

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

I would like to transform one Sql server table into another. 我想将一个Sql server表转换为另一个。

Original 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

After transformation 转型后

    Returns      Pre0Month   Pre1Month    Pre2Month

    Portfolio   -0.0001      0.0122       0.0176
    Benchmark   -0.0025      0.0269       0.0244

Considering the name of the table to be MyTable, you can pivot it the following way: 考虑到表的名称是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;

This requires a combination of PIVOT and UNPIVOT: 这需要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;

Result is the following: 结果如下:

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

Because you are using SQL-Server you can use the pivot command to do what you want. 因为您使用的是SQL-Server,所以您可以使用pivot命令执行您想要的操作。 check it out here: https://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx 在这里查看: https//technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx

You can use the DateDiff function to separate the dates out by month easily too. 您可以使用DateDiff函数轻松地逐月分隔日期。 https://msdn.microsoft.com/en-us/library/ms189794.aspx https://msdn.microsoft.com/en-us/library/ms189794.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM