如何在动态Pivot Sql Server 2008中排序或订购日期

时间:2014-02-21 04:40:26

标签: sql-server sql-server-2008

  

我有下表

enter image description here

旋转后的表格如下。如何在透视列中维护日期顺序?

enter image description here

2 个答案:

答案 0 :(得分:1)

以下是您可以动态执行此操作的方法。

    CREATE TABLE TEST
(
  NAME VARCHAR(10),
  DATECOL DATE,
  VALUECol INT   
)

INSERT INTO TEST
VALUES
('A', '01/JAN/2014', 10),
('B', '01/JAN/2014', 20),
('A', '26/JAN/2014', 20),
('B', '26/JAN/2014', 30),
('A', '01/FEB/2014', 40),
('B', '01/FEB/2014', 50),
('A', '26/FEB/2014', 60),
('B', '26/FEB/2014', 70)


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

select @colsPivot = STUFF((SELECT distinct ',' + QUOTENAME(DATECOL) 
                    from TEST
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query 
  = 'select *
      from
      (
        select NAME,DATECOL,VALUECOL
        from TEST

      ) x1
      pivot
      (
        max(VALUECOL)
        for DATECOL in ('+ @colspivot +')
      ) p'

    exec(@query)

SQL Fiddle

上查看此内容

答案 1 :(得分:0)

我有自己的方法来解决这个问题

CREATE TABLE #TEMP (Name varchar(10), [DATE] datetime, Value int)
INSERT #TEMP VALUES 
('A','01/JAN/2014',10), 
('B','01/JAN/2014',20), 
('A','26/JAN/2014',20), 
('B','26/JAN/2014',30), 
('A','01/FEB/2014',40), 
('B','01/FEB/2014',50), 
('A','26/FEB/2014',60),
('B','26/FEB/2014',70)

现在我们将格式 DD / MMM / YYYY 分配给变量 (注意:[日期]列应为日期时间/日期类型)

DECLARE @cols NVARCHAR (MAX)

SELECT @cols = COALESCE (@cols + ',[' + REPLACE(CONVERT(NVARCHAR, [DATE], 106), ' ', '/') + ']', 
               '[' + REPLACE(CONVERT(NVARCHAR, [DATE], 106), ' ', '/') + ']')
               FROM    (SELECT DISTINCT [DATE] FROM #TEMP) PV  
               ORDER BY [DATE]

旋转后,列将处于完美的日期顺序,格式为 DD / MMM / YYYY

DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT * FROM 
             (
                 SELECT Name,REPLACE(CONVERT(NVARCHAR, [DATE], 106), '' '', ''/'') [DATE] , value FROM #TEMP
             ) x
             PIVOT 
             (
                 SUM(value)
                 FOR [DATE] IN (' + @cols + ')
            ) p;' 

EXEC SP_EXECUTESQL @query

像这样,您可以转换为任何日期格式,并可以在透视列中维护日期的顺序 通过编辑Pivot语句的SELECT @cols和内部SELECT中的转换类型