2012-07-12 72 views
3

我在SQL Server 2005中使用this query(我只使用了比较方便的2008插入方法),我需要在网格输出中将(null)替换为0。SQL Server 2005使用0填充数据透视表

无论如何要做到这一点?

+2

对,其实这里有完全相同的问题/答案已经在SO:[** 1 **](http://stackoverflow.com/questions/3297132/replace-null-values-in -sql-pivot),[** 2 **](http://stackoverflow.com/questions/9567807/null-in-sql-server-pivot),[** 3 **](http:// stackoverflow .com/questions/10325538/how-to-replace-the-null-values-in-a-pivot-output-with-zeroes),[** 4 **](http://stackoverflow.com/questions/ 7304081 /更换空从 - 结果 - 的情况下的查询)。我在谷歌上搜索了'sql服务器数据透视表替换为null的站点:stackoverflow.com'。 – mellamokb 2012-07-12 19:42:32

+0

#1我见过,甚至包括在我的小提琴。其他人会解决我的问题。我想谷歌>所以搜索框? – gooddadmike 2012-07-12 21:20:57

+0

这就是我倾向于做的事情。因为让我们面对它,谷歌几乎总是比网站自己的搜索框更好地搜索网站:) – mellamokb 2012-07-13 14:05:16

回答

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