在SQL Server中使用交叉和联合CTE进行透视

时间:2015-10-05 20:45:25

标签: sql sql-server pivot

我有这个:

SELECT * 
FROM 
   (SELECT  
        tblLandAreas.LandAreaId, Sysproperties.Name, 
        tblLandAreaPropertyValues.Value 
    FROM tbllandareas
    LEFT JOIN tblLandAreaProperties ON tblLandAreaProperties.LandAreaId = tblLandAreas.LandAreaId
    LEFT JOIN tblLandAreaPropertyValues ON tblLandAreaProperties.LandAreaPropertyId = tblLandAreaPropertyValues.LandAreaPropertyId
    CROSS JOIN Sysproperties SysProperties 
    WHERE 
        SysProperties.SysPropertyId = tblLandAreaProperties.SysPropertyId 
        AND tblLandAreas.LandAreaId = '1175' 

    UNION ALL

    SELECT DISTINCT 
        (tblLandAreas.LandAreaId), Sysproperties.Name, null 
    FROM tbllandareas
    LEFT JOIN tblLandAreaProperties ON tblLandAreaProperties.LandAreaId = tblLandAreas.LandAreaId
    LEFT JOIN tblLandAreaPropertyValues ON tblLandAreaProperties.LandAreaPropertyId = tblLandAreaPropertyValues.LandAreaPropertyId
    CROSS JOIN Sysproperties SysProperties  
    WHERE tblLandAreas.LandAreaId = '1175') AS SourceTable
PIVOT
(
    MAX(SourceTable.Value)
    FOR SourceTable.Name IN (SELECT Name FROM Sysproperties) 
) AS PivotTable

我收到此错误:

  

第15行,第15行,第1行,第22行   关键字' SELECT'。

附近的语法不正确      

Msg 102,Level 15,State 1,Line 22
  ')'附近的语法不正确。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您需要在您的for子句中使用静态列表,或者您可以使用动态列表,如下所示

DECLARE @col NVARCHAR(MAX)

SELECT @col=   STUFF(( select distinct ',[' +   Name +']'FROM Sysproperties for XML path ('')),1,1,'')

DECLARE @query NVARCHAR(MAX)


SET @query = '
SELECT * 
FROM 
(SELECT  
    tblLandAreas.LandAreaId, Sysproperties.Name, 
    tblLandAreaPropertyValues.Value 
FROM tbllandareas
LEFT JOIN tblLandAreaProperties ON tblLandAreaProperties.LandAreaId = tblLandAreas.LandAreaId
LEFT JOIN tblLandAreaPropertyValues ON tblLandAreaProperties.LandAreaPropertyId = tblLandAreaPropertyValues.LandAreaPropertyId
CROSS JOIN Sysproperties SysProperties 
WHERE 
    SysProperties.SysPropertyId = tblLandAreaProperties.SysPropertyId 
    AND tblLandAreas.LandAreaId = ''1175'' 

UNION ALL

SELECT DISTINCT 
    (tblLandAreas.LandAreaId), Sysproperties.Name, null 
FROM tbllandareas
LEFT JOIN tblLandAreaProperties ON tblLandAreaProperties.LandAreaId = tblLandAreas.LandAreaId
LEFT JOIN tblLandAreaPropertyValues ON tblLandAreaProperties.LandAreaPropertyId = tblLandAreaPropertyValues.LandAreaPropertyId
CROSS JOIN Sysproperties SysProperties  
WHERE tblLandAreas.LandAreaId = ''1175'') AS SourceTable
PIVOT
(
MAX(SourceTable.Value)
FOR SourceTable.Name IN (' + @col + ')
) AS PivotTable'

EXEC SP_EXECUTESQL @query