将列名称移动到行

时间:2017-10-12 08:00:25

标签: sql sql-server

我有一个日期为列名enter image description here

的表格

但我想将这些日期放在一行中的多列中,如下所示:

Date       Index
20170806   9206
20170813   8041
20170820   8861
20170827   8356

如何在SQL Server中执行此操作

4 个答案:

答案 0 :(得分:1)

您可以使用UNPIVOT

SELECT * FROM MyTable 
UNPIVOT([Date] For [Index] IN( [20170806], [20170813], [20170820], [20170827])) UNPVT

此外,如果您想动态制作它,也可以使用此查询。

DECLARE @ColNames NVARCHAR(MAX) 
    = STUFF(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
        (SELECT T.* FROM (VALUES(1)) AS DUMY(ID) LEFT JOIN MyTable T ON 1=2 FOR XML AUTO, ELEMENTS XSINIL )
        ,'<T xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">','')
        ,'</T>','')
        ,'_x0032_','2')
        ,' xsi:nil="true"/>','] ')
        ,'<',',[') ,1,1,'')


DECLARE @SqlQ NVARCHAR(MAX) 
    = 'SELECT * FROM MyTable UNPIVOT([Date] For [Index] IN( ' + @ColNames  + ')) UNPVT'

EXEC sp_executesql @SqlQ

答案 1 :(得分:1)

如果您希望获得更多动态解决方案而不是对所有列进行硬编码,则以下脚本应该有效:

IF OBJECT_ID('TestTable') IS NOT NULL 
DROP TABLE TestTable;

CREATE TABLE TestTable
(
    [20170806] INT NOT NULL,
    [20170813] INT NOT NULL,
    [20170820] INT NOT NULL,
    [20170827] INT NOT NULL
)

INSERT INTO TestTable VALUES (9206, 8041, 8861, 8356)


DECLARE @cols NVARCHAR(MAX),
        @sql  NVARCHAR(MAX)

SELECT  @cols = COALESCE(@cols + ',', '') + QUOTENAME(c.COLUMN_NAME)
FROM   INFORMATION_SCHEMA.[COLUMNS] AS c
WHERE  c.TABLE_NAME = 'TestTable'

SET @sql = '
SELECT [Date],
       [Index]
FROM   TestTable 
       UNPIVOT([Index] FOR [Date] IN ('+ @cols +')) AS up'

exec sp_executesql @sql;

答案 2 :(得分:0)

您可以使用枢轴,例如:

但是,我不知道你确切的表名

select field_names
from table_name
pivot
( index
for index in ( Date, Index)
) pivot

但是有用的文章是

&#34; https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx&#34;

答案 3 :(得分:0)

设计表(变量)结构如下。 希望它符合您的表结构。

DECLARE @data TABLE
(
    [20170806] INT,
    [20170813] INT,
    [20170820] INT,
    [20170827] INT
)

INSERT INTO @data VALUES (9206, 8041, 8861, 8356)

SELECT * FROM @data

您可以使用UNPIVOT语句。 If you have dynamic columns, check this

SELECT [Date],[Index]
FROM
@data  
UNPIVOT 
(
  [Index] FOR [Date] IN ([20170806], [20170813], [20170820], [20170827])
) AS unpivotTable;

,输出

enter image description here