0

我有以下查询,它总是给出错误。有人可以帮我解决这个问题吗?

“关键字'@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
4

1 回答 1

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)
于 2013-01-10T16:30:37.800 回答