SQL Server中的结果集求和
假设我有如下表格:SQL Server中的结果集求和,sql,Sql,假设我有如下表格: Class Student Maths English ------------------------------------ 1 a 50 60 1 b - 60 2 c 70 50 2 d 40 - 我需要一个SQL查询来生成这个结果集: Score Maths English Total
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
请帮助。试试这个:
SELECT
Class,
sum(Maths) as Maths,
sum(English) as English,
sum(Maths+English) as Total
FROM
table
Group by
Class with Rollup
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进行一些调整。尝试以下方法:
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进行一些调整。
我用过一个看起来不那么优雅的组合
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
我用过一个看起来不那么优雅的组合
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
要获得总计,您需要卷起牙床cjk。我需要T-sql语法,这是完美的。要获得总计,您需要rollup tooThanks cjk。我需要T-sql语法,这是完美的。