PIVOT上的SQL Server语法错误

时间:2012-06-14 07:15:25

标签: sql-server pivot

任何人都可以帮我解决PIVOT表语法错误,因为我是第一次使用它。

DECLARE @sql AS varchar(max)<br/>
DECLARE @pivot_list AS varchar(max) <br/>
DECLARE @select_list AS varchar(max) <br/>

SELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + CONVERT(varchar,    STATE_NAME) + ']'<br/>
      ,@select_list = COALESCE(@select_list + ', ', '') + '[' + CONVERT(varchar, STATE_NAME) + '] AS [' + CONVERT(varchar, STATE_NAME) + ']'
FROM (
SELECT DISTINCT name as STATE_NAME
    FROM k12_dms_states
) AS PIVOT_CODES

SET @sql = '
 SELECT COUNT(k12_dms_contacts_institution_jobtitles.id)  as total_count 
,k12_dms_job_titles.title as job_title,' + @select_list + '
FROM k12_dms_institution_master 
INNER JOIN k12_dms_contacts_institution_jobtitles ON k12_dms_institution_master.id = k12_dms_contacts_institution_jobtitles.inst_id 
INNER JOIN k12_dms_job_titles ON k12_dms_job_titles.id = k12_dms_contacts_institution_jobtitles.job_title_id 
GROUP BY k12_dms_job_titles.title
PIVOT (
total_count
FOR STATE_NAME IN (
    ' + @pivot_list + '
)
) AS pvt
 '

  PRINT @sql

  EXEC (@sql)

我收到此错误: -

  

Msg 156,Level 15,State 1,Line 8
  关键字'PIVOT'附近的语法不正确。

1 个答案:

答案 0 :(得分:1)

PIVOT属于FROM clause。它需要在任何GROUP BY子句之前发生。

(基于评论的进一步编辑,试图纠正):

SET @sql = '
 SELECT 
k12_dms_job_titles.title as job_title,' + @select_list + '
FROM k12_dms_institution_master 
INNER JOIN k12_dms_contacts_institution_jobtitles ON k12_dms_institution_master.id = k12_dms_contacts_institution_jobtitles.inst_id 
INNER JOIN k12_dms_job_titles ON k12_dms_job_titles.id = k12_dms_contacts_institution_jobtitles.job_title_id 
PIVOT (
COUNT(k12_dms_contacts_institution_jobtitles.id)
FOR STATE_NAME IN (
    ' + @pivot_list + '
)
) AS pvt
 '