SQL Query to get the Sum of all column values in the last row of a resultset along with row sum (group by)

前端 未结 3 598
予麋鹿
予麋鹿 2021-01-12 16:30

Can someone please help me to write a query to obtain the TCS and TRS?

ID  Jan Feb Mar TRS
1   4   5   6   15
2   5   5   5   15
3   1   1   1   3
TCS 10  11         


        
相关标签:
3条回答
  • 2021-01-12 17:08

    This query will do the job

    select cast(id as varchar(20)), Jan, Feb, Mar , Jan + Feb + Mar as TRS
    from table1
    
    union all
    
    select 'TCS' as id, SUM(Jan) Jan, SUM(Feb) Feb, SUM(Mar) Mar, null as TRS
    from table1
    

    The first column will be returned as varchar as this way you have a mix of integers (id) and the text TCS.

    0 讨论(0)
  • 2021-01-12 17:12

    You can use GROUP BY and WITH ROLLUP, like this:

    SELECT
        id
    ,   SUM(jan) as jan
    ,   SUM(feb) as feb
    ,   SUM(mar) as mar
    ,   SUM(jan+feb+mar) as TRS
    FROM test
    GROUP BY id WITH ROLLUP
    

    Live demo on sqlfiddle.

    0 讨论(0)
  • 2021-01-12 17:12

    select Sum(Jan + Feb + Mar) As TRS

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