我遵循了使用数据透视表创建水平和垂直总计的教程,因此我得到了这个查询
CREATE PROCEDURE logszxcx
AS
/* COLUMNS HEADERS */
DECLARE @columnHeaders NVARCHAR (MAX)
select @columnHeaders = STUFF((SELECT ',' + QUOTENAME(log_date)
from tbl_log
group by log_date
order by log_date
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
/* GRAND TOTAL COLUMN */
DECLARE @GrandTotalCol NVARCHAR (MAX)
SELECT @GrandTotalCol = COALESCE (@GrandTotalCol + 'ISNULL ([' +
CAST (log_date AS VARCHAR) +'],0) + ', 'ISNULL([' + CAST(log_date AS VARCHAR)+ '],0) + ')
FROM tbl_log ORDER BY log_date
SET @GrandTotalCol = LEFT (@GrandTotalCol, LEN (@GrandTotalCol)-1)
/* GRAND TOTAL ROW */
DECLARE @GrandTotalRow NVARCHAR(MAX)
SELECT @GrandTotalRow = COALESCE(@GrandTotalRow + ',ISNULL(SUM([' +
CAST(log_date AS VARCHAR)+']),0)', 'ISNULL(SUM([' + CAST(log_date AS VARCHAR)+']),0)')
FROM tbl_log ORDER BY log_date
/* MAIN QUERY */
DECLARE @FinalQuery NVARCHAR (MAX)
SET @FinalQuery = 'SELECT *, ('+ @GrandTotalCol + ')
AS [Grand Total] INTO #temp_MatchesTotal
FROM
(SELECT task_id,
log_date
FROM tbl_log
) A
PIVOT
(
COUNT (*)
FOR ColName
IN ('+@columnHeaders +')
) B
ORDER BY task_id
SELECT * FROM #temp_MatchesTotal UNION ALL
SELECT ''Grand Total'','''','+@GrandTotalRow +',
ISNULL (SUM([Grand Total]),0) FROM #temp_MatchesTotal
DROP TABLE #temp_MatchesTotal'
-- PRINT 'Pivot Query '+@FinalQuery
EXECUTE(@FinalQuery)
GO
这会创建一个存储过程但是当我尝试运行sp时,我在创建的主查询上出错了
SELECT *, ('+ @GrandTotalCol + ')
AS [Grand Total] INTO #temp_MatchesTotal
FROM
(SELECT task_id,
log_date
FROM tbl_log
) A
PIVOT
(
COUNT (*)
FOR ColName
IN ('+@columnHeaders +')
) B
ORDER BY task_id
SELECT * FROM #temp_MatchesTotal UNION ALL
SELECT ''Grand Total'','''','+@GrandTotalRow +',
ISNULL (SUM([Grand Total]),0) FROM #temp_MatchesTotal
DROP TABLE #temp_MatchesTotal
它表示我在* on count附近有一个不正确的语法,我无法弄清楚它有什么问题。在此先感谢。