日期:2014-05-20  浏览次数:20390 次

求一SQL查询语句
数据库中的表
时间       科目     成绩
2月         语文     80
2月         数学     70
2月         英语     76
2月         物理     70
1月         语文     76
1月         数学     65
1月         英语     70
1月         物理     68

查询后的表
时间       科目     上月成绩   本月成绩
2月         语文       76                   80
2月         数学       65                   70
2月         英语       70                   76
2月         物理       68                   70

怎么实现上面的查询结果


------解决方案--------------------
select * from a
left join a b on(a.kemu=b.kemu)
where a.shijian=b.shijian-1
------解决方案--------------------
date1 = 2月
date2 = 1月
select 时间 , 科目 , 上月成绩 ,成绩 AS 本月成绩
from
(
select * from tablename where 时间=date1
)tablenew1 left join
(
select 科目,成绩 as 上月成绩
from tablename
where 时间 = date2
) tablenew2 on tablenew1.科目=tablenew2.科目

------解决方案--------------------
用自连接就可以了。
select a.时间,a.科目,b.成绩 as 上月成绩,a.成绩 as 本月成绩
from t a, t b
where a.时间 = b.时间
and substr(a.时间,1,1)= substr(sysdate(),5,1)
and substr(b.时间,1,1)= substr(sysdate(-1),5,1)
上月表达好像不对,不知道怎么写,可以参考一下
------解决方案--------------------
select 时间 , 科目 , 上月成绩 ,成绩 AS 本月成绩
from
(
select * from tablename where 时间=date1
)tablenew1 left join
(
select 科目,成绩 as 上月成绩
from tablename
where 时间 = date2
) tablenew2 on tablenew1.科目=tablenew2.科目
--------------
做不到?
------解决方案--------------------


create table test
(
Months nvarchar(12),
Subject nvarchar(12),
Result decimal(18,2),
)
insert into test values( '2月 ', '语文 ',80)
insert into test values( '2月 ', '数学 ',70)
insert into test values( '2月 ', '英语 ',76)
insert into test values( '2月 ', '物理 ',70)

insert into test values( '1月 ', '语文 ',76)
insert into test values( '1月 ', '数学 ',65)
insert into test values( '1月 ', '英语 ',70)
insert into test values( '1月 ', '物理 ',68)

declare @Pm nvarchar(12) --上月,具体你可以根据当月自己计算
declare @Cm nvarchar(12) --本月
select @Pm= '1月 '
select @Cm= '2月 '
select @Cm as '时间 ',P.Subject,P.PResult as '上月成绩 ',C.CResult as '本月成绩 ' from
(
select Months,Subject, Result as PResult from test where Months=@Pm
)P
left join
(
select Months,Subject,Result as CResult from test where Months=@Cm
)C on C.Subject=P.subject
from test

Drop table test
------解决方案--------------------
这语句经典,不过还是写出来了,测试了上,可以: