1

假设我有如下表格:

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

请帮忙。

4

3 回答 3

3
SELECT
    Class,
    sum(Maths) as Maths,
    sum(English) as English,
      sum(Maths+English) as Total
FROM
    table
Group by
    Class with Rollup
于 2012-07-13T06:59:02.310 回答
2

sql小提琴

我使用了一个看起来不那么优雅的联合

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
于 2012-07-13T07:47:59.393 回答
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 进行一些调整。

于 2012-07-13T07:00:47.870 回答