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

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 

------其他解决方案--------------------
select sum(Match),sum(English),sum(C#),sum(SQL),sum(java) where U_format =2 group by Per
------其他解决方案--------------------
还有一个问题:与上述问题的表没有半点关系,重新的一张临时表#Temp和C,如果C表中的U_Type = 'N'则将临时表#Temp内的内容全部清空,应该怎么做? IF C._Type = 'N' Then truncate Table #Temp,这样貌似不对啊,怎么改正?
------其他解决方案--------------------
select *, (case when month(date) in (1,2,3) then 1 when month(date) in (4,5,6) then 2 
 when month(date) in (7,8,9) then 3 else 4 end) datein from 表 
然后根据datein分组
------其他解决方案--------------------
能不能给出点数据, 怎么感觉U_Format跟Month会冲突
------其他解决方案--------------------
引用:
能不能给出点数据, 怎么感觉U_Format跟Month会冲突

好像是的,那把U_Format放在C表中呢?
数据:R表中:
  Name   Match   English  C#   SQL   JAVA  Month   Per