有个表table1:
ID Code Qty
1 001 1
2 002 3
3 001 5
4 001 4
5 003 1
6 002 2
7 002 1
8 003 4
9 003 3
想得到各 Code 对应 Qty 值最大的那组数据,像这样:
ID Code Qty
3 001 5
2 002 3
8 003 4
这样写OK不?
Select a.ID, a.Code, a.Qty
From table1 a,
( select Code, MAX(Qty)
from table1
group by Code
) b
Where a.Code = b.Code and a.Qty = b.Qty
------解决方案--------------------
-- 方法1
select a.ID,a.Code,a.Qty
from table1 a,
(select Code,
max(Qty) 'Qty'
from table1
group by Code) b
where a.Code=b.Code and a.Qty=b.Qty
-- 方法2
select a.*
from table1 a
where not exists
(select 1
from table1 b
where b.Code=a.Code and b.Qty>a.Qty)
------解决方案--------------------
我个人习惯这样写:
Select a.ID, a.Code, a.Qty
From table1 a
where exists (select 1 from
( select Code, MAX(Qty)Qty
from table1
group by Code
) b where a.code=b.code and a.qty=b.qty)
------解决方案--------------------
方法三:
select * from table1 as a where qty=(select max(qty) from table1 where code=a.code )
------解决方案--------------------
如果ID序号没什么要求的话
select Max(ID)ID,Code,Max(Qty)Qty from Table1 group by Code

------解决方案--------------------
分组后也可以套个子查询
if object_id('table1') is not null
drop table table1
go
create table table1
(
Id int identity not null,
Code nvarchar(3),
Qty int
)
insert into table1 select '001',1 union all