动态数据透视表组由

时间:2015-02-02 09:40:23

标签: sql-server-2008 pivot

Plz帮助 这是动态数据透视表,我该如何进行分组

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME(name)
FROM (SELECT DISTINCT name FROM #tmpBusdatewise) AS name


SET @DynamicPivotQuery = 
  N'SELECT datewise, ' + @ColumnName + '
    FROM #tmpBusdatewise
    PIVOT(SUM(totlcnt) 
          FOR name IN (' + @ColumnName + ') ) AS PVTTable'-- group by ' + @columnname


EXEC sp_executesql @DynamicPivotQuery

由于 萨米尔

2 个答案:

答案 0 :(得分:0)

问题是源表必须在内部查询

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME(name)
FROM (SELECT DISTINCT name FROM #tmpBusdatewise) AS name


SET @DynamicPivotQuery = 
  N' -- Your pivoted result comes here
    SELECT datewise, ' + @ColumnName + '
    FROM 
    (
        -- Source table should in a inner query
        SELECT datewise,name,totlcnt
        FROM #tmpBusdatewise
    )AS P
    PIVOT
    (     
          -- Select the values from derived table P
          SUM(totlcnt) 
          FOR name IN (' + @ColumnName + ') 
    )AS PVTTable'

EXEC sp_executesql @DynamicPivotQuery

答案 1 :(得分:0)

谢谢,现在它已经解决了。

实际上还没有计算

我添加了

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)


DECLARE @ColumnName AS NVARCHAR(MAX)


declare @colmn as nvarchar(max)

SELECT @colmn= ISNULL(@colmn + ',','')  
+'sum('+ QUOTENAME(name)+') as ' + QUOTENAME(name)
FROM (SELECT DISTINCT name FROM #tmpBusdatewise) AS name

 
SELECT
 @ColumnName= ISNULL(@ColumnName + ',','') 
+ QUOTENAME(name)
FROM 
(SELECT DISTINCT name FROM #tmpBusdatewise) AS name


 
SET
 @DynamicPivotQuery = 
N'SELECT datewise, ' + @colmn + '
    FROM #tmpBusdatewise
    PIVOT(SUM(totlcnt) 
          FOR name IN ('
 + @ColumnName + ') ) AS PVTTable group by datewise'
--print(@DynamicPivotQuery)

EXEC sp_executesql @DynamicPivotQuery