首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

取每组最大值中的一条数据解决办法

2013-04-21 
取每组最大值中的一条数据CREATEtable TEST1(FID int, ItemID varchar(1), QTY int)insert into TEST1sele

取每组最大值中的一条数据


CREATE  table TEST1(FID int, ItemID varchar(1), QTY int)

insert into TEST1
select 1, 'a', 10 union all
select 2, 'a', 20 union all
select 3, 'a', 40 union all
select 4, 'a', 30 union all
select 5, 'a', 40 union all
select 1, 'b', 15 union all
select 2, 'b', 45 union all
select 3, 'b', 25 union all
select 4, 'b', 35 union all
select 5, 'b', 45 

希望查询结果为
2b45
3a40
即,取每组itemid的最大值对应数据的一条(最大值有多条时,只取一条)
不知如何才能实现,请指教 SQL ?每组?最大值
[解决办法]

select * from TEST1 t
where QTY=(select max(QTY) from TEST1 where ItemID=t.ItemID)
and FID=(select min(FID) from TEST1 where ItemID=t.ItemID and QTY=t.QTY)
/*
FID         ItemID QTY
----------- ------ -----------
2           b      45
3           a      40
*/

热点排行
Bad Request.