如何查询group by中的某列的最大值的返回列

lg314 2009-11-13 12:23:43
说的不是很清楚

create table #ls(barcode varchar(30),vendorid char(6),indate datetime,price float)
insert into #ls(barcode,vendorid,indate,price)
select '11','01','2009-01-01',0.1 union all
select '11','02','2009-02-01',0.7 union all
select '11','03','2009-02-03',0.9 union all
select '11','01','2009-05-01',0.2 union all
select '11','02','2009-06-01',1.4 union all
select '11','03','2009-07-03',1.8 union all
select '21','01','2009-01-01',0.1 union all
select '21','02','2009-02-01',0.7 union all
select '21','03','2009-02-03',0.9 union all
select '21','01','2009-05-01',0.3 union all
select '21','02','2009-06-01',2.1 union all
select '21','03','2009-07-03',2.7



select b.barcode,b.vendorid,b.price from (select barcode,vendorid,max(indate) as indate from #ls group by barcode,vendorid) a
left join #ls b on a.barcode=b.barcode and a.vendorid=b.vendorid and a.indate=b.indate


就是说找出barcode和vendorid对应的indate最晚日期的price
...全文
266 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
白头老汉 2009-11-14
  • 打赏
  • 举报
回复
做一个内连接,用indate=max(indate)
select barcode,vendorid,price from #ls as a where a.indate=(select max(indate) from #ls where #ls.barcode=a.barcode and #ls.vendorid=a.vendorid)
SQL77 2009-11-13
  • 打赏
  • 举报
回复
select * from #ls t
where INDAETE=(select MAX(INDATER) from #ls where barcode=t.barcode and vendorid=t.vendorid )
lg314 2009-11-13
  • 打赏
  • 举报
回复
呵呵,非常不错
百年树人 2009-11-13
  • 打赏
  • 举报
回复
select t.barcode,t.vendorid,t.price 
from #ls t
where not exists(select 1 from #ls where
barcode=t.barcode and vendorid=t.vendorid and indate>t.indate)
水族杰纶 2009-11-13
  • 打赏
  • 举报
回复
--try
select * from #ls t
where not exists(select 1 from #ls where barcode=t.barcode and vendorid=t.vendorid
and indate>t.indate)
lg314 2009-11-13
  • 打赏
  • 举报
回复
直接返回的方法,不用嵌套
zxkid 2009-11-13
  • 打赏
  • 举报
回复
运用RANK()函数

27,579

社区成员

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

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