2012-07-12 63 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