SQL的一个简单问题:按期计算时需要每两个月的数据相加,详见如下:
在R(学生成绩)表中有这么几个字段:Match(数学成绩)、English(英语成绩)、C#(C语言成绩)、SQL(JAVA成绩)、JAVA(计算机组成原理成绩)、U_Format(由此来决定是按月计算还是按期计算)、Per(按期计算时的期:1期、2期、3期、4期,每一期包含三个月)、Month(按月计算时的月,一共12个月) 要求:当U_format为1时则按月计算,即计算每一个月的成绩:select Match,English,C#,SQL,JAVA from R where U_Format = 1这个好做,但是如果是U_format = 2时则按期,将会三个月一加,我写一个大体意思,是不正确的,求改正:select sum(Match),sum(English),sum(C#),sum(SQL),sum(java) where U_format =2
这样的话是把12个月的加在一起了,但是我想要三个月一加,三个月一加,怎么改正????
[最优解释]
create table R
(
name char(4),
match int,
english int,
C# int,
sql int,
java int,
[month] int,
per int
)
insert into R select '1001',82,83,84,90,91,1,1
union all select '1001',82,83,84,90,91,2,1
union all select '1001',82,83,84,90,91,3,1
union all select '1002',66,83,84,90,91,1,1
union all select '1002',82,83,84,90,91,2,1
union all select '1002',90,83,84,90,91,3,1
union all select '1003',66,83,84,90,91,3,1
union all select '1003',82,83,84,90,91,4,2
union all select '1003',90,83,84,90,91,5,2
union all select '1003',90,83,84,90,91,6,2
union all select '1004',82,83,84,90,91,4,2
union all select '1004',90,83,84,90,91,5,2
union all select '1004',90,83,84,90,91,6,2
--每月
select MONTH, sum(match)match,sum(english)english,sum(C#)C#,sum(sql)sql,sum(java)java from R group by month
--每期
select per, sum(match)match,sum(english)english,sum(C#)C#,sum(sql)sql,sum(java)java from R group by per
create table D
(
id int,
del char(1)
)
insert into D values(1,'N')
--触发器
create trigger trigger_delete on D
for update
as
declare @a varchar(20)
select @a=del from D where id=1
if(@a='Y' )
begin
delete from R
end
go
update d set del='Y' where id=1
1001 82 83 84 90 91 1 1
1001 90 92 94 88 82 2 1
1001 78 77 88 90 91 3 1
(1001这位同学参加了1月份、2月份、3月份的考试,其他月份的考试没有参加)
1002 66 87 98 67 90 1 1
1002 82 83 84 90 91 2 1
1002 90 92 94 88 82 3 1
(1002这位同学参加了1月份、2月份、3月份的考试,其他月份的考试没有参加)
1003 78 77 88 90 91 3 1
1003 66 87 98 67 90 4 2
1003 82 83 84 90 91 5 2
1003 90 92 94 88 82 6 2
(1003这位同学参加了3月份、4月份、5月份的考试、6月份的考试,其他月份的考试没有参加)
1004 78 77 88 90 91 4 2
1004 66 87 98 67 90 5 2
1004 82 83 84 90 91 6 2
(1004这位同学参加了4月份、5月份、5月份的考试,其他月份的考试没有参加)
C表中:
U_Format
1
2
参加考试的同学,如果C表中的U_Format是1,那么得到的成绩就是每个月的,列出每个月的成绩来,如果是U_Format是2那么就得到三个月一加的成绩,在某一期中只参加了一个月或者两个月的考试则其他未参加考试月份的成绩为0,直接加0,这么一来是不是清晰了很多?
[其他解释]
还有一个问题:在D表中有一个IsDele字段,如果为‘Y’则删除R表中的数据,保留表结构,要求:不放在R表查询语句where中做而是放在外面,比如说(这个例子是错的,这是表示个意思,求改正!)
IF D.IsDele = 'Y' Then Delete From R
[其他解释]
呵呵,非常感谢!