日期:2014-05-17  浏览次数:20531 次

关于sql分组统计的问题
表结构如下
学生   课程  成绩    学分
张三   语文  40       2
张三   数学  60       5
张三   语文  80       2
张三   英语  54       3
张三   英语  38       3
张三   数学  70       5

统计该学生所学课程的总学分,即:张三总共选了语文、数学、英语三门课程,对应学分为2,5,8,所以总学分为10分

统计该学生及格课程的学分,如60分及格的话,张三英语不及格,所以只统计语文与数学的学分,即7分

用sql语句该如何写

------最佳解决方案--------------------

IF(OBJECT_ID('TA','U') IS NOT NULL) DROP TABLE TA
CREATE TABLE TA(Sname VARCHAR(10),Cname VARCHAR(10),Score INT, xf TINYINT)
INSERT INTO TA
SELECT '张三','语文',40,2 UNION ALL
SELECT '张三','数学',60,5 UNION ALL
SELECT '张三','语文',80,2 UNION ALL
SELECT '张三','英语',54,3 UNION ALL
SELECT '张三','英语',38,3 UNION ALL
SELECT '张三','数学',70,5  

SELECT Sname, SUM(xf) AS '总学分' FROM(
SELECT  Sname,Cname,xf FROM TA 
GROUP BY Sname,Cname,xf 
 )AS A GROUP BY Sname
---------
SELECT Sname, SUM(xf) AS '获得学分' FROM(
SELECT  Sname,Cname,xf FROM TA 
WHERE Score>=60
GROUP BY Sname,Cname,xf)AS A
GROUP BY Sname

------其他解决方案--------------------

if OBJECT_ID('Score') is not null
drop table Score
create table Score
(
Name nvarchar(20),
Course nvarchar(20),
Score int,
Credit int
)
go

insert into Score
select '张三','语文',40,2 union all
select '张三','数学',60,5 union all
select '张三','语文',80,2 union all
select '张三','英语',54,3 union all
select '张三','英语',38,3 union all
select '张三','数学',70,5

select *From Score

--统计该学生所学课程的总学分
select S.Name,SUM(S.Credit) CreditAll from
(select Name,Course,Credit from Score
group by Name,Course,Credit) as S
group by Name


--统计该学生及格课程的学分

select Name,SUM(Credit) CreditAll from
(select Name,Course,Credit, MAX(Score) MaxScore from Score 
group by Name,Course,Credit
having max(Score)>=60) as S
group by Name

------其他解决方案--------------------
作业自己做。
------其他解决方案--------------------
with tb(学生,课程,成绩,学分)
as(
select '张三','语文',40,2 union all
select '张三','数学',60,5 union all
select '张三','语文',80,2 union all
select '张三','英语',54,3 union all
select '张三','英语',38,3 union all
select '张三','数学',70,5
),
source as(
select 学生,max(学分) 学分,max(成绩) 成绩 from tb group by 学生,课程)
select 学生,sum(学分)总学分,sum(case when 成绩>=60 then 学分 else 0 end)获得学分 from source group by 学生