如何在Sql中使用日期标题来转动表格

时间:2018-03-23 10:47:56

标签: sql sql-server

我有以下带有日期标题的临时表如何取消透视此表

enter image description here I need This type result

我需要喜欢这种类型的结果

2 个答案:

答案 0 :(得分:1)

以下是您问题的解决方案:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

select @colsUnpivot 
  = stuff((select ','+quotename(C.name)
           FROM sys.columns c
           WHERE c.object_id = OBJECT_ID('table') 
           for xml path('')), 1, 1, '')

set @query 
  = 'select sno,EmpId, Name, Date, Value
     from table
     unpivot
     (
        Date 
        FOR EmpId IN ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;

我使用了动态查询,因为如果您不知道表格中有多少列。 您还可以使用以下静态查询:

SELECT sno, EmpId, Name, Date, Value
FROM 
   (SELECT *
   FROM table) p
UNPIVOT
   (Date FOR EmpId IN 
      (01-Mar-18,02-Mar-18,03-Mar-18,04-Mar-18,05-Mar-18)
)AS unpvt;

答案 1 :(得分:0)

尝试以下脚本:

  SELECT [s#no], [Emp#ID], [Name], [Date], [Shiftid]
    FROM 
    (SELECT * FROM table_name) SRC
    UNPIVOT
   ([Date] FOR [Emp#ID] 
    IN ([01-Mar-18], [02-Mar-18], [03-Mar-18], [04-Mar-18], [05-Mar-18])
   ) UNPVT;