日期:2014-05-18  浏览次数:20719 次

求简单SQL语句

portid cococd services
9 1 b2
4 1 m2
5 9 m2

要得到这样的结果:

portid cococd services
9 1 b2
5 9 m2

也就是按services分组,并取得最大portid的记录
例如上面的m2有两条,就只留下portid=5的



------解决方案--------------------
create table ss(portid int ,cococd int,services varchar(10))
insert into ss select 9,1,'b2'
insert into ss select 4,1,'m2'
insert into ss select 5,9,'m2'

select max(portid) as portid,max(cococd) as cococd,services from ss group by services
------解决方案--------------------
哦。 不好意思理解错楼主的意思了

应该是这样的
SQL code

select * from ss  where portid in (select max(portid) from ss group by services)

------解决方案--------------------
select table1.* from table1,(select max(portid) as portid,services from table1 group by services) t2 where table1.portid=t2.portid and table1.services=t2.services;
------解决方案--------------------
portid cococd services 
9 1 b2 
4 1 m2 
5 9 m2 

select a.* from tb a,
(select services,max(portid) portid from tb group by services) b
where a.services = b.services and a.portid = b.portid
------解决方案--------------------
select * from tablename T where portid in(
select top 1 portid from tablename where services=T.services order by protid desc)
------解决方案--------------------

select * from #temp t where not exists
(select 1 from #temp where portid>t.portid and services=t.services)
------解决方案--------------------
select services from t1 where cocode in (select code from t2)
------解决方案--------------------
create table t11(services varchar(10),cocode int)
insert into t11 select 'b2',1
insert into t11 select 'm2',9

create table t12(code int)
insert into t12 select 6
insert into t12 select 9

select t11.services from t11,t12 where t11.cocode=t12.code
------解决方案--------------------
select services from t1 where cococd in(select code from t2)
------解决方案--------------------
8楼的嵌套与9楼的联接~
------解决方案--------------------
同意9楼的