分组排序后,如何取得组的第一条记录!!!

lulesheng1983 2004-12-10 09:49:57
数据:

日期 编号 数量
---------------------------------
2004-09-01 001 500
2004-09-02 001 450
2004-09-01 002 300
2004-09-02 002 400

如何取得
---------------------------------
2004-09-02 001 450
2004-09-02 002 400
---------------------------------

取得按编号分组日期倒序排列,取top 1 记录


...全文
764 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
Softlee81307 2005-01-27
  • 打赏
  • 举报
回复
select * from 表 a
where 日期=(select top 1 日期 from 表 where 编号=a.编号 order by 日期 desc)
NETFUNNER 2005-01-27
  • 打赏
  • 举报
回复
有用....
vinsonshen 2004-12-10
  • 打赏
  • 举报
回复

select * from 表 as a where not exists (select * from 表 where 编号=a.编号 and 日期>a.日期)
zjcxc 2004-12-10
  • 打赏
  • 举报
回复
--或:
select a.* from 表 a,(select 编号,日期=max(日期) from 表 group by 编号)b
where a.编号=b.编号 and a.日期=b.日期

--或:
select * from 表 a
where not exists(
select * from 表 where 编号=a.编号 and 日期>a.日期)
zjcxc 2004-12-10
  • 打赏
  • 举报
回复
--忘了加排序,改一下:

select * from 表 a
where 日期=(select top 1 日期 from 表 where 编号=a.编号 order by 日期 desc)
zjcxc 2004-12-10
  • 打赏
  • 举报
回复
select * from 表 a
where 日期=(select top 1 日期 from 表 where 编号=a.编号)
老宛 2004-12-10
  • 打赏
  • 举报
回复
--测试
create table #yourtable(
日期 datetime,
编号 varchar(10),
数量 numeric)
insert into #yourtable select '2004-09-01','001',500
insert into #yourtable select '2004-09-02','001',450
insert into #yourtable select '2004-09-01','002',300
insert into #yourtable select '2004-09-02','002',400


select a.*,b.数量 from (select 编号,max(日期) 日期 from #yourtable group by 编号) a,#yourtable b
where a.日期=b.日期 and a.编号=b.编号
order by a.编号 asc,a.日期 desc
drop table #yourtable
子陌红尘 2004-12-10
  • 打赏
  • 举报
回复
select a.日期 ,
a.编号 ,
a.数量
from
表 a
inner join
(select 编号,max(日期) as 日期 from 表 group by 编号) b
on
a.编号 = b.编号
and
a.日期 = b.日期
netmin 2004-12-10
  • 打赏
  • 举报
回复
和我的问题的一样?
freddy2003 2004-12-10
  • 打赏
  • 举报
回复
参见:
http://community.csdn.net/Expert/topic/3602/3602230.xml?temp=.7934229

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧