如何将给定结构转换为预期结构?

时间:2015-07-13 06:24:43

标签: sql sql-server tsql pivot pivot-table

我在图像中有查询结果,类似于90个日期,所以如何将对象分组并将日期作为列并计入各自的日期。

enter image description here

提前致谢!!

2 个答案:

答案 0 :(得分:2)

您可以使用动态交叉表来执行此操作:

SQL Fiddle

DECLARE @sql1 VARCHAR(4000) = ''
DECLARE @sql2 VARCHAR(4000) = ''
DECLARE @sql3 VARCHAR(4000) = ''

SELECT @sql1 = 
'SELECT
    [Object]' + CHAR(10)

SELECT @sql2 = @sql2 +
'   , MAX(CASE WHEN [Date] = CAST(''' + CONVERT(VARCHAR(8), [Date], 112) + ''' AS DATE) THEN [count] END) AS ' + QUOTENAME([Date]) + CHAR(10)
FROM(
    SELECT DISTINCT [Date] FROM tbl
)t
ORDER BY [Date]

SELECT @sql3 = 
'FROM tbl
GROUP BY [Object]
ORDER BY [Object]'

PRINT(@sql1 + @sql2 + @sql3)
EXEC (@sql1 + @sql2 + @sql3)

<强> RESULT

| Object | 2015-01-01 | 2015-01-02 |
|--------|------------|------------|
|      1 |         10 |         34 |
|      2 |         20 |         46 |
|      3 |        130 |         78 |
|      4 |         40 |         89 |
|      5 |         55 |         45 |

这是PRINT命令的输出:

SELECT
    [Object]
    , MAX(CASE WHEN [Date] = CAST('20150101' AS DATE) THEN [count] END) AS [2015-01-01]
    , MAX(CASE WHEN [Date] = CAST('20150102' AS DATE) THEN [count] END) AS [2015-01-02]
FROM tbl
GROUP BY [Object]
ORDER BY [Object]

答案 1 :(得分:2)

您可以使用SQL Server PIVOT关系运算符

DECLARE   @SQLQuery AS NVARCHAR(MAX)
DECLARE   @PivotColumns AS NVARCHAR(MAX)

--Get unique values of pivot column  
SELECT   @PivotColumns= COALESCE(@PivotColumns + ',','') + QUOTENAME([Date])
FROM (SELECT DISTINCT [Date] FROM [dbo].[PivotExample]) AS PivotExample



--Create the dynamic query with all the values for 
--pivot column at runtime
SET   @SQLQuery = 
    N'SELECT ObjectId, ' +   @PivotColumns + '
    FROM [dbo].[PivotExample] 
    PIVOT( SUM(COUNT) 
          FOR [Date] IN (' + @PivotColumns + ')) AS P'


EXEC sp_executesql @SQLQuery