动态SQL获取数据透视表

时间:2018-10-15 21:11:53

标签: sql dynamic pivot

我在动态构建数据透视表时遇到了一些问题。构建要执行的查询字符串时,出现此错误: 公用表表达式已定义但未使用。 这是我的代码段:

`USE [DatabaseAccessLayer.PhoneBookContext]

 DECLARE @COLUMNS AS NVARCHAR(MAX), @QRY_ NVARCHAR(500);
 DECLARE @TABLE_ NVARCHAR(10) = 'tempTable'
 DECLARE @Month INT = '06'; 

 WITH ColumnNames AS (
    SELECT DISTINCT pht.Name AS 'PhoneType'
    FROM Records.People pp, Records.PhoneNumberTypes pht, Records.Phones ph
    WHERE pp.PersonId = ph.PersonId AND ph.PhoneTypeId = pht.PhoneTypeId AND 
          MONTH(pp.Birthday) = @MONTH
    )-- SELECT * FROM ColumnNames
    ,ColumnMap AS (
    SELECT C.PhoneType
    FROM ColumnNames C  LEFT JOIN ColNames CN 
    ON REPLACE(C.PhoneType, C.PhoneType, C.PhoneType + ' Phone') = 
       CN.ColumnId)--SELECT * FROM ColumnMap

 SELECT @COLUMNS = ( SELECT  QUOTENAME(PhoneType)+','
                        FROM ColumnNames AS ColumnName  
                        FOR XML PATH('')
                   )       
 SELECT @COLUMNS = SUBSTRING(@COLUMNS, 1, LEN(@COLUMNS)-1);
 PRINT @COLUMNS;--testing purpose

 WITH tempTable AS(
        SELECT TOP (100)pp.FirstName AS Name ---See how to remove top clause --when using ORDER BY???
                       ,CONVERT(NVARCHAR(5), pp.Birthday, 103) AS Birthday             
                       ,ph.Number
       FROM Records.People pp, Records.Phones ph, Records.PhoneNumberTypes pht 
       WHERE pp.PersonId = ph.PersonId AND ph.PhoneTypeId = pht.PhoneTypeId 
             AND MONTH(pp.Birthday) = @Month
       ORDER BY 'Birthday', Name
      )SELECT @QRY_ = 'SELECT FirstName, Birthday,' + @COLUMNS+'    
                        FROM(SELECT FirstName, Birthday
                              ,Number
                              FROM' +@TABLE_ +') x
                       PIVOT
                       (
                        MAX(Number)
                        FOR Name IN ('+@COLUMNS+')
                       )p'

  `PRINT @QRY_
   EXECUTE sp_executesql @QRY_;`

[在此处输入图片描述] [2]

图像(在链接:在此处输入图像描述)显示了我要完成的工作。

先谢谢 T。

enter image description here

0 个答案:

没有答案