2012-07-13 102 views
1

假設我有表如下:總結的結果集在SQL Server

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 

請幫助。

回答

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中的小調整。

+0

爲了得到總計你也需要彙總 – Madhivanan 2012-07-13 07:02:23

+0

謝謝cjk。我需要T-sql語法,這很完美。 – 2012-07-13 07:05:48

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

感謝Madhivanan – 2012-07-13 07:06:30

+0

+1從未見過彙總之前 - 喜歡它! – whytheq 2012-07-13 07:49:37

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