SQL拆分结果为多列

时间:2014-10-10 19:30:25

标签: sql datetime split sql-server-2012 pivot

我想将结果从包含在多个列中的表中拆分出来。 根据原始查询的结果,每列是一个月中的某一天。

请考虑下表:

VALUE    |  TIMESTAMP
1        | 2014-10-01 00:00:00
22       | 2014-10-01 12:00:00
333      | 2014-10-02 00:00:00
2000     | 2014-10-02 12:00:00
55       | 2014-10-03 00:00:00
11       | 2014-10-03 12:00:00

我想获得一个结果,其中第一列是时间,后面的每一列都是一个月中的一天(从1到31)

这样的事情:

Time      |  Day1  |  Day2  |  Day3  | ......
00:00:00  |    1   |   333  |  55    | ......
12:00:00  |    22  |  2000  |  11    | ......

我能够实现一天,例如Day1

Time      |  Day1  
00:00:00  |    1   
12:00:00  |    22  

SELECT cast(TIMESTAMP as time) [time], VALUE as Day1
FROM TABLE1 
WHERE TIMESTAMP>='2014-10-01' and TIMESTAMP<='2014-10-02'

如何获得剩余的一天专栏?

1 个答案:

答案 0 :(得分:0)

为此,您需要使用动态数据透视查询。

在像这样的非动态查询中,您需要提前提供一个天数列表:

SELECT 
  [Time], [Day 1],[Day 2],[Day 3]
FROM (
  SELECT 
    VALUE,
    LEFT(CAST(TIMESTAMP AS TIME),5) [TIME], 
    CONCAT('Day ', DAY(TIMESTAMP)) D
  FROM TABLE1
) AS Source
PIVOT (SUM(Value) FOR D IN ([Day 1],[Day 2],[Day 3]) 
) AS Pivoted

但是使用动态查询,您首先会建立天数列表,然后将其注入模型查询中:

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

SELECT @cols= ISNULL(@cols + ',','') + QUOTENAME(CONCAT('Day ', D))
FROM (SELECT DISTINCT DAY(TIMESTAMP) D FROM Table1) AS Days

SET @sql =
  N'SELECT [Time], ' + @cols + '
    FROM (
     SELECT 
       VALUE,
       LEFT(CAST(TIMESTAMP AS TIME),5) [TIME], 
       CONCAT(''Day '', DAY(TIMESTAMP)) D
     FROM TABLE1
    ) AS Source
    PIVOT(SUM(Value)
          FOR D IN (' + @cols + ')) AS Pivoted'

EXEC sp_executesql @sql

请注意,上述查询并不确保日期在同一年/月内,您应该为此添加一项检查,或将查询限制为给定的月/年。

结果:

Time  Day 1       Day 2       Day 3
----- ----------- ----------- -----------
00:00 1           333         55
12:00 22          2000        11

Sample SQL Fiddle