sql中的动态数据透视

时间:2014-04-27 04:58:32

标签: sql sql-server pivot-table

我使用pivot函数进行了以下sql查询。

我不知道我有什么错误

此查询。请帮我解决这个问题

DECLARE @DEPT VARCHAR(MAX)            
  SELECT @DEPT=COALESCE('@DEPT+','['+DEPTID+']','['+DEPTID+'])  
  FROM DEPARTMENTDEMO  
  DECLARE @QUERY VARCHAR(MAX)  
  SET @QUERY='SELECT '+@DEPT+'    
FROM (SELECT DEPTID  
FROM DEPARTMENTDEMO     
)AS SOURCETABLE  
PIVOT  
(DEPTNAME FOR DEPTID IN ('+@DEPT+')  
)AS PIVOTTABLE'

EXEC SP_EXECUTESQL @QUERY

2 个答案:

答案 0 :(得分:1)

首先,用于创建列列表的表达式在错误的位置有一些引号:

SELECT @DEPT=COALESCE(@DEPT+',['+DEPTID+']','['+DEPTID+']')

另外,请查看here以获取创建列列表的正确方法(它支持语法并保证元素的顺序)。

对于实际的PIVOT表达式,您必须在列上使用一些聚合。试试MAX:

SET @QUERY= '
SELECT '+@DEPT+'    
FROM (
    SELECT DEPTID, DEPTNAME  
    FROM DEPARTMENTDEMO     
) AS SOURCETABLE  
PIVOT (
    MAX(DEPTNAME) FOR DEPTID IN ('+@DEPT+')  
) AS PIVOTTABLE'

答案 1 :(得分:0)

前几天我正在玩动态旋转!这是我在创建时创建的功能齐全的测试脚本。虽然它基于CROSS JOIN示例,但它应包含一些有用的见解。我希望你能收集一些关于如何获得理想结果的想法。

IF OBJECT_ID(N'dbo.Strikes','U') IS NOT NULL
    DROP TABLE dbo.Strikes;

CREATE TABLE dbo.Strikes(
    Dimension nvarchar(10) NOT NULL PRIMARY KEY ,
    DimVal smallint DEFAULT 0);

INSERT INTO dbo.Strikes (Dimension, DimVal)
VALUES (N'Fire',5), (N'Water',4), (N'Earth',3), (N'Air',2), (N'Spirit',1), (N'George',0);


/* Dynamic Pivot Exmple */

--declare variables and cursor
DECLARE @PvtClm varchar(MAX)
DECLARE @PTmp AS varchar(10)
DECLARE PvtCsr CURSOR FOR
    SELECT DISTINCT Dimension 
    FROM dbo.Strikes 
    ORDER BY Dimension
--open and fill pivot column string
OPEN PvtCsr
    SET @PvtClm = N'[' 
    FETCH NEXT FROM PvtCsr INTO @PTmp
    WHILE @@FETCH_STATUS = 0
        BEGIN
            SET @PvtClm = @PvtClm + RTRIM(@PTmp) + N'], ['
            FETCH NEXT FROM PvtCsr INTO @PTmp
        END
--kill cursor and finish pivot string
CLOSE PvtCsr
DEALLOCATE PvtCsr

--strip bogus end characters to finish pivot string
SET @PvtClm = LEFT(@PvtClm,(LEN(@PvtClm)-3));

--PRINT @PvtClm

--set the dynamic pivot sql string
DECLARE @DynPivot nvarchar(MAX)
SET @DynPivot = N'
WITH CrJoin AS (
    SELECT S1.Dimension AS SourceElement,
           S2.Dimension AS TargetElement,
           S1.DimVal - S2.DimVal AS Modifier
    FROM dbo.Strikes AS S1
        CROSS JOIN dbo.Strikes AS S2)

SELECT SourceElement, ' + @PvtClm + '
FROM CrJoin
PIVOT( 
    MAX(CrJoin.Modifier) 
    FOR CrJoin.TargetElement IN(' + @PvtClm + ')
    ) AS PvT;'

--PRINT @DynPivot

--run the pivot
EXEC sp_executesql @stmt = @DynPivot;


IF OBJECT_ID(N'dbo.Strikes','U') IS NOT NULL
    DROP TABLE dbo.Strikes;