--Declare variables
DECLARE @SQLQuery AS NVARCHAR(MAX)
DECLARE @PivotColumns AS NVARCHAR(MAX)
--Get unique values of pivot column
SELECT @PivotColumns= COALESCE(@PivotColumns + ',','') + QUOTENAME(MSG_Description)
from(select MSG_Description From MenuSecurityGroup ) AS PivotExample
SELECT @PivotColumns
--Create the dynamic query with all the values for
--pivot column at runtime
SET @SQLQuery =
N'SELECT EMP_EmployeeID, EMP_LastName, EMP_FirstName,
EMP_EMailAddress,EMP_StatusCode, EMP_SFM_SupervisorConsole,
EMP_SFM_WorkCenterConsole,
EMP_SFM_SC_ProdAnalyzer ' + @PivotColumns + '
FROM [dbo].[EMP]
LEFT JOIN EmployeeMenuSecurityGroup EMSG on EMP.EMP_RecordID = EMSG.ESG_EMP_RecordID
LEFT JOIN MenuSecurityGroup MSG on EMSG.ESG_MSG_RecordID = MSG.MSG_RecordID
PIVOT( max(MSG_Description)
FOR MSG_Description IN (' + @PivotColumns + ')) AS P '
SELECT @SQLQuery
--Execute dynamic query
EXEC sp_executesql @SQLQuery
答案 0 :(得分:0)
您只需要在PIVOT之前添加派生表,并且只包含您希望在最终结果中看到的字段以及您要去PIVOT的字段。
SET @SQLQuery = N'
SELECT EMP_EmployeeID, EMP_LastName, EMP_FirstName,
EMP_EMailAddress,EMP_StatusCode, EMP_SFM_SupervisorConsole,
EMP_SFM_WorkCenterConsole, EMP_SFM_SC_ProdAnalyzer,
' + @PivotColumns + '
FROM ( SELECT EMP_EmployeeID, EMP_LastName, EMP_FirstName,
EMP_EMailAddress,EMP_StatusCode, EMP_SFM_SupervisorConsole,
EMP_SFM_WorkCenterConsole, EMP_SFM_SC_ProdAnalyzer,
MSG_Description
FROM [dbo].[EMP]
LEFT JOIN EmployeeMenuSecurityGroup EMSG on EMP.EMP_RecordID = EMSG.ESG_EMP_RecordID
LEFT JOIN MenuSecurityGroup MSG on EMSG.ESG_MSG_RecordID = MSG.MSG_RecordID
) t
PIVOT (
MAX(MSG_Description)
FOR MSG_Description IN (' + @PivotColumns + ')
) p'