calculate Row Wise Sum - Sql server

后端 未结 3 1148
一个人的身影
一个人的身影 2020-12-09 23:32

This is My table :

ID              Q1         Q2           Q3            Q4
----------------------------------------------------------------
20130712                 


        
3条回答
  •  粉色の甜心
    2020-12-10 00:04

    You haven't shown your query attempt, but it's probably something like this:

    SELECT
      ID, Q1, Q2, Q3, Q4,
      Q1 + Q2 + Q3 + Q4 AS "Total"
    FROM MyTable
    

    If any of the Q1, Q2, Q3, or Q4 values are null, Q1 + Q2 + Q3 + Q4 will be null. To treat the nulls as zero and get a proper sum, do this instead:

    SELECT
      ID, Q1, Q2, Q3, Q4,
      COALESCE(Q1,0) + COALESCE(Q2,0) + COALESCE(Q3,0) + COALESCE(Q4,0) AS "Total"
    FROM MyTable
    

    The COALESCE function will return the first non-null value in the list.

提交回复
热议问题