求助!SQL对表中部分数据进行分组问题
求教各位大神啊!我想对表里的部分数据进行分组
例如:
--给个例子参考
CREATE TABLE StudentGrade(
stuId CHAR(4), --学号
subId INT, --课程号
grade INT, --成绩
PRIMARY KEY (stuId,subId)
)
GO
--表中数据如下
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '001 ',1,97);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '001 ',2,50);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '001 ',3,70);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '002 ',1,92);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '002 ',2,80);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '002 ',3,30);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '003 ',1,93);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '003 ',2,95);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '003 ',3,85);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '004 ',1,73);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '004 ',2,78);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '004 ',3,87);
GO
stuIdsubIdgrade
001 197
001 250
001 370
002 192
002 280
002 330
003 193
003 295
003 385
004 173
004 278
004 387
stuIdsubIdgrade
001 0217
002 192
002 280
002 330
003 193
003 295
003 385
004 173
004 278
004 387
--给个例子参考
CREATE TABLE StudentGrade(
stuId CHAR(4), --学号
subId INT, --课程号
grade INT, --成绩
PRIMARY KEY (stuId,subId)
)
GO
--表中数据如下
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '001 ',1,97);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '001 ',2,50);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '001 ',3,70);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '002 ',1,92);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '002 ',2,80);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '002 ',3,30);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '003 ',1,93);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '003 ',2,95);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '003 ',3,85);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '004 ',1,73);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '004 ',2,78);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES( '004 ',3,87);
GO
select stuId,
case when stuId = '001'
then 0
else subId
end subId,
SUM(grade) as grade
from StudentGrade
group by stuId,
case when stuId = '001'
then 0
else subId
end
order by stuId
/*
stuIdsubIdgrade
001 0217
002 192
002 280
002 330
003 193
003 295
003 385
004 173
004 278
004 387
*/