calculate Row Wise Sum - Sql server

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

This is My table :

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


        
相关标签:
3条回答
  • 2020-12-09 23:56

    Expanding on Roman Pekar, If you're using a temp table and want to do this, you need to use tempdb like this:

    select
    @stmt = isnull(@stmt + ', ', '') + '[' + name + ']',
    @stmt1 = isnull(@stmt1 + ', ', '') + '(' + '[' + name + ']'+  ')'
    from tempdb.sys.columns
    where object_id = object_id('tempdb..##TempTable') and name not in ('ID')
    --ID would be one of the column names you DONT want to sum.
    --also notice the double pound sign. you need to declare your temp table with double pounds or it wont work
    --also notice how I put brackets around name, that's because my columns weren't working because they had slashes in their names.
    --the rest of the code is the same
    select @stmt =
              'select Date_Packed, ' + @stmt + '' + 
              ', (select sum(S.Q) from (values ' + @stmt1 +
              ') as S(Q) where S.Q is not null) as [Total] ' +
              'from tempdb..##TempTableas T'
              print @stmt
    
    exec sp_executesql @stmt = @stmt
    --don't forget to drop it
              drop table ##TempTable
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 00:13

    Don't know if it there's a shorter way, but the most elegant I can do is:

    select
        ID, Q1, Q2, Q3, Q4,
        (
             select sum(S.Q)
             from (values (Q1), (Q2), (Q3), (Q4)) as S(Q)
             where S.Q is not null
        ) as [Total]
    from Table1 as T
    

    sql fiddle demo

    If you want dynamic SQL, try something like

    declare @stmt nvarchar(max), @stmt1 nvarchar(max)
    
    select
        @stmt = isnull(@stmt + ', ', '') + name,
        @stmt1 = isnull(@stmt1 + ', ', '') + '(' + name + ')'
    from sys.columns
    where object_id = object_id('Table1') and name not in ('ID')
    
    select @stmt =
              'select ID, ' + @stmt + 
              ', (select sum(S.Q) from (values ' + @stmt1 +
              ') as S(Q) where S.Q is not null) as [Total] ' +
              'from Table1 as T'
    
    exec sp_executesql @stmt = @stmt
    

    sql fiddle demo

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