重塑表SQL

时间:2018-10-18 08:26:07

标签: sql sql-server

我正在使用SQL,目前有一个大表,其中包含按日期排序的1000个帐户的数据:

ID   July 2018    August 2018    September 2018    …
1       10            20             30
2       50            40             10
3       20            10             80

我需要调整表格的形状,以便表格显示如下:

   ID     Month          Value   
    1   July 2018         10 
    1   August 2018       20    
    1   September 2018    30
    :        :             :

我不知道该怎么做,或者甚至可能。我尝试在SQL中使用pivot函数,但未成功。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:1)

您可以使用APPLY

SELECT t.id, tt.*
FROM table t CROSS APPLY
     ( VALUES ('July 2018', [July 2018]), 
              ('August 2018', [August 2018]), 
              ('September 2018', [September 2018])
     ) tt (Month, Val);

答案 1 :(得分:0)

您可以使用unpivot-它可以在MSSQL中使用

select t.id, up.months, up.value
from tablename t
unpivot
(
  value
  for months in ([July 2018], [August 2018], [September 2018])
) up;

答案 2 :(得分:0)

您可以在UNION运算符的帮助下进行尝试:

select id, 'July 2018' as Month, July2018 as value from <table>
UNION
select id, 'August 2018' as Month, August2018 as value from <table>
UNION
select id, 'September 2018' as Month, September2018 as value from <table>