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
由于 萨米尔
答案 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