使用pivot生成动态列

时间:2013-01-10 16:24:10

标签: sql-server

我有以下查询总是给出错误。有些身体可以帮助我    解决这个问题?

  

“关键字'@stqsql'附近的语法不正确。”

我的代码是:

  declare @strsql nvarchar(max)
  set @strsql=select merchantid from employee

  select * 
  from 
  (
     Select s.employeeid,
           COUNT(*) as TotCount 
     from Employee s  
     GROUP BY s.employeeid 
  )as a
  pivot (avg(TotCount) for employeeid IN ('+@stqsql+')) AS NoOfRec

1 个答案:

答案 0 :(得分:0)

不幸的是,您尝试获取动态列的方式不起作用。您将不得不使用类似于以下内容的东西:

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

-- this gets the list of values that you want to pivot
select @colsPivot = STUFF((SELECT distinct ', ' + QUOTENAME(merchantid ) 
                    from employee 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

-- since you are use a dynamic list you have to use dynamic sql
set @query = 'SELECT ' + @colsPivot + ' from 
             (
                SELECT s.employeeid,
                    COUNT(*) as TotCount
                FROM Employee s
                GROUP BY s.employeeid
            ) src
            pivot 
            (
                avg(TotCount)
                for employeeid  in (' + @colsPivot + ')
            ) p '

execute(@query)