Replacing NULL with 0 in a SQL server query

后端 未结 12 1088
情书的邮戳
情书的邮戳 2020-11-28 02:39

I have developed a query, and in the results for the first three columns I get NULL. How can I replace it with 0?

  Select c.rund         


        
相关标签:
12条回答
  • 2020-11-28 03:08

    Use COALESCE, which returns the first not-null value e.g.

    SELECT COALESCE(sum(case when c.runstatus = 'Succeeded' then 1 end), 0) as Succeeded
    

    Will set Succeeded as 0 if it is returned as NULL.

    0 讨论(0)
  • 2020-11-28 03:11

    When you say the first three columns, do you mean your SUM columns? If so, add ELSE 0 to your CASE statements. The SUM of a NULL value is NULL.

    sum(case when c.runstatus = 'Succeeded' then 1 else 0 end) as Succeeded, 
    sum(case when c.runstatus = 'Failed' then 1 else 0 end) as Failed, 
    sum(case when c.runstatus = 'Cancelled' then 1 else 0 end) as Cancelled, 
    
    • SQL Fiddle Demo
    0 讨论(0)
  • 2020-11-28 03:11
    UPDATE TableName SET ColumnName= ISNULL(ColumnName, 0 ) WHERE Id = 10
    
    0 讨论(0)
  • 2020-11-28 03:14

    With coalesce:

    coalesce(column_name,0)
    

    Although, where summing when condition then 1, you could just as easily change sum to count - eg:

    count(case when c.runstatus = 'Succeeded' then 1 end) as Succeeded,
    

    (Count(null) returns 0, while sum(null) returns null.)

    0 讨论(0)
  • 2020-11-28 03:14

    by following previous answers I was losing my column name in SQL server db however following this syntax helped me to retain the ColumnName as well

    ISNULL(MyColumnName, 0) MyColumnName
    
    0 讨论(0)
  • 2020-11-28 03:16

    When you want to replace a possibly null column with something else, use IsNull.

    SELECT ISNULL(myColumn, 0 ) FROM myTable
    

    This will put a 0 in myColumn if it is null in the first place.

    0 讨论(0)
提交回复
热议问题