求相同记录行如何取最大值,相关SQL语句,求教!
有一表四个字段:fid int,fprice dec(5,2),fsuid int,fdate datetime
fid与fsuid组成的记录行相同时,取最大日期(fdate)的对应的价格(fprice),示例如下:
fid fprice fsuid fdate
1 2.1 2 2005-09-09
1 2.2 2 2005-10-10
1 3.3 2 2006-01-01
2 3.3 1 2003-09-09
2 5.5 1 2005-09-09
2 3.2 2 2005-09-09
2 5.5 2 2005-09-15
结果应如下 :
1 3.3 2 2006-01-01
2 5.5 1 2005-09-09
2 5.5 2 2005-09-15
谢谢!
问题点数:20、回复次数:6Top
1 楼iuhxq(小灰)回复于 2006-03-04 18:35:47 得分 3
select t1.fid,max(t1.fprice),t1.fsuid,t1.fdate datetime from table1 t1,table1 t2
where t1.fid=t2.fid and t1.fsuid = t2.fsuid and t1.fdate = t2.fdate
试试Top
2 楼zhaoanle(zhao)回复于 2006-03-04 18:45:37 得分 10
--测试数据
create table #表A (fid int,fprice dec(5,2),fsuid int,fdate datetime)
insert #表A select 1, 2.1, 2, '2005-09-09'
insert #表A select 1, 2.2, 2, '2005-10-10'
insert #表A select 1, 3.3, 2, '2006-01-01'
insert #表A select 2, 3.3, 1, '2003-09-09'
insert #表A select 2, 5.5, 1, '2005-09-09'
insert #表A select 2, 3.2, 2, '2005-09-09'
insert #表A select 2, 5.5, 2, '2005-09-15'
--查询
select distinct a.* from #表A a,(select fid,fsuid,max(fdate) as 'fdate' from #表A group by fid,fsuid) b
where a.fid=b.fid and a.fsuid=b.fsuid and a.fdate=b.fdate order by a.fid
/*结果
fid fprice fsuid fdate
----------- ------- ----------- ------------------------------------------------------
1 3.30 2 2006-01-01 00:00:00.000
2 5.50 1 2005-09-09 00:00:00.000
2 5.50 2 2005-09-15 00:00:00.000
(所影响的行数为 3 行)Top
3 楼flashspider(还没想好)回复于 2006-03-05 22:27:08 得分 0
谢谢二位了,不过小灰可能没有理解我的意思,我要求是最大日期对应的价格,而不是最大价格,不过幸苦了大家了,再次感谢!Top
4 楼ReViSion(和尚)回复于 2006-03-05 22:33:21 得分 7
--Try
--测试数据
create table #A (fid int,fprice dec(5,2),fsuid int,fdate datetime)
insert #A select 1, 2.1, 2, '2005-09-09'
insert #A select 1, 2.2, 2, '2005-10-10'
insert #A select 1, 3.3, 2, '2006-01-01'
insert #A select 2, 3.3, 1, '2003-09-09'
insert #A select 2, 5.5, 1, '2005-09-09'
insert #A select 2, 3.2, 2, '2005-09-09'
insert #A select 2, 5.5, 2, '2005-09-15'
select * from #A a
where not exists
(select 1 from #A where fid=a.fid and fsuid=a.fsuid and fdate>a.fdate)Top
5 楼flashspider(还没想好)回复于 2006-03-11 16:15:47 得分 0
多谢各位了!Top
6 楼flashspider(还没想好)回复于 2006-03-12 12:10:56 得分 0
TO:ReViSion
虽然执行结果是对的,但我不太了解执行过程,不太明白这个SQL语句,能不能说明一下???
谢谢了!Top




