- SQL code
--测试数据-----------------------------------------1.--添加--表1CREATE TABLE [dbo].[MyUserInfo]( [myname] [nvarchar](20) not null,--姓名 [kemu] [nvarchar](20) not NULL,--语文 数学等。 [mynumber] [int] not NULL--学号) ON [PRIMARY] --数据INSERT INTO [dbo].[MyUserInfo]([myname],[kemu],[mynumber]) VALUES('jack','语文' ,10001)INSERT INTO [dbo].[MyUserInfo]([myname],[kemu],[mynumber]) VALUES('jack','数学' ,10001)INSERT INTO [dbo].[MyUserInfo]([myname],[kemu],[mynumber]) VALUES('Fans','语文' ,10002)INSERT INTO [dbo].[MyUserInfo]([myname],[kemu],[mynumber]) VALUES('Fans','数学' ,10002)--【当 [dbo].[MyUserInfo] 选择学号10001,则返回】select * from MyUserInfo where mynumber=10001--jack 语文 10001--jack 数学 10001--表2CREATE TABLE [dbo].[MyAchievement]( [kemu] [nvarchar](20) not null,--语文 数学等。 [Fenshu] [int] not NULL,--语文 数学等。 [mydate] [datetime]) ON [PRIMARY] insert into [dbo].[MyAchievement]([kemu],[Fenshu],[mydate]) values ('语文',80,'2012-8-1')insert into [dbo].[MyAchievement]([kemu],[Fenshu],[mydate]) values ('语文',80,'2012-9-1')insert into [dbo].[MyAchievement]([kemu],[Fenshu],[mydate]) values ('语文',80,'2012-8-8')insert into [dbo].[MyAchievement]([kemu],[Fenshu],[mydate]) values ('数学',80,'2012-8-1')insert into [dbo].[MyAchievement]([kemu],[Fenshu],[mydate]) values ('语文',80,'2012-10-1')insert into [dbo].[MyAchievement]([kemu],[Fenshu],[mydate]) values ('数学',80,'2012-9-1')--select * from MyAchievement--问题:从表一10001--得到 语文 和 数学, 语文和数学 在表2中时间最大的值。--希望得到的是时间最大的, 这个2条书面--语文 80 2012-10-01 00:00:00.000--数学 80 2012-09-01 00:00:00.000
------解决方案--------------------
select kemu,Fenshu,mydate
from (select a.kemu,b.fenshu,b.mydate,row_number()over(order by b.mydate desc) rn from MyUserInfo a,MyAchievement b
where a.kemu = b.kemu and a.mynumber = '10001') where rn = 1
------解决方案--------------------
- SQL code
--這樣取select * from MyAchievement a where exists(select 1 from MyUserInfo where mynumber=10001 and MyUserInfo.kemu=a.kemu) and mydate=(select max(mydate) from [MyAchievement] b where a.[kemu]=b.[kemu]);