SQL Server 2005使用0填充数据透视表

时间:2012-07-12 19:37:44

标签: tsql sql-server-2005 null pivot

我在SQL Server 2005中有this query(我仅使用更方便的2008插入方法),我需要在网格输出中将(null)替换为0。

无论如何要做到这一点?

1 个答案:

答案 0 :(得分:4)

您可以使用ISNULL()功能。见SQL Fiddle

SELECT 'lessonid          response ->'
   , isnull([0], 0) as [0]
  , isnull([1], 0) as [1]
  , isnull([2], 0) as [2]
  , isnull([3], 0) as [3]
  , isnull([4], 0) as [4]
FROM (
    SELECT lessonid AS 'lessonid          response ->'
        ,ISNULL(response,0) as response
        ,count(response) AS respcnt
    FROM tblRChoices
    GROUP BY lessonid
        ,response
    ) TableResponse
PIVOT(SUM(respcnt) FOR response IN (
            [0]
            ,[1]
            ,[2]
            ,[3]
            ,[4]
            )) ResponsePivot