在sql server中使用group by with pivot和unpivot

时间:2016-01-06 07:16:00

标签: sql-server pivot unpivot

我在sql中使用pivot和unpivot并对其进行动态查询。但我的问题是,我收到一条错误说为'P'多次指定了'May-2015'专栏。。你们可以帮我使用 GROUP BY 吗?查询如下:

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+'],[' , '') + [Month]
FROM Table1
SELECT @listStr = '[' + @listStr + ']'

DECLARE @Query VARCHAR(8000)
SET @Query = '
select [System],' + @listStr +
'from
(
  select [Month],Col1,Col2,Col3,Col4     
  from Table1
) as T
unpivot
(
  Value for [System] in (Col1,Col2,Col3,Col4)
) as U
pivot
(
  sum(Value) for [Month] in (' + @listStr + ')
) as P'

EXECUTE(@Query)

由于

0 个答案:

没有答案