在SQL Server中汇总结果集

时间:2012-07-13 06:54:51

标签: sql

假设我有以下表格:

Class  Student  Maths  English
------------------------------------
 1      a        50       60
 1      b        -        60
 2      c        70       50
 2      d        40        -

我需要一个SQL查询来生成这个结果集:

Score        Maths   English  Total
--------------------------------------
 1             50       120     170
 2             110       50     160
Grand Total    160       170    330

请帮忙。

3 个答案:

答案 0 :(得分:3)

SELECT
    Class,
    sum(Maths) as Maths,
    sum(English) as English,
      sum(Maths+English) as Total
FROM
    table
Group by
    Class with Rollup

答案 1 :(得分:2)

sql fiddle

我使用了看起来不那么优雅的联盟

create table the_table 
(
  class int,
  student varchar(5),
  maths int,
  english int,
)
insert into the_table
values
( 1, 'a', 50, 60),
( 1, 'b', 0, 60),
( 2, 'c', 70, 50),
( 2, 'd', 40, 0)

select 
  [class] = convert(varchar(50),class)  
  , sum(maths) maths
  , sum(english) english
  , sum(maths + english) total
from the_table
group by
  class
union
select 
  [class] = 'Grand Total'
  , sum(maths) maths
  , sum(english) english
  , sum(maths + english) total
from the_table

答案 2 :(得分:1)

试试这个:

SELECT 
    ISNULL(Class, 'Grand Total') as Score, 
    sum(Maths) as Maths, 
    sum(English) as English,
    sum(Maths) + sum(English) as Total
FROM 
    table 
GROUP BY 
    ISNULL(Class, 'Grand Total')
WITH ROLLUP

请注意,这是T-SQL语法,可能需要对MySql或Oracle进行一些调整。