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

求解最小值有关问题

2013-02-25 
求解最小值问题create table #T(name char(10),id char(1),countxint)insert into #T select A,1,20un

求解最小值问题
create table #T(name char(10),id char(1),countx  int)
insert into #T 
select 'A','1',20
union
select 'A','2',30
union
select 'B','1',30
union
select 'B','2',20
union
select 'C','1',40

select #t.name,#t.id,#t.countx from #T inner join 
(select name,min(id) id from #t group by name) b
on #T.name=b.name and #T.id=b.id

drop table #T

上面需要进行inner join 连接才能完成
有没有更好的方法,更简洁的方法
[解决办法]


create table #T(name char(10),id char(1),countx  int)
insert into #T 
select 'A','1',20
union
select 'A','2',30
union
select 'B','1',30
union
select 'B','2',20
union
select 'C','1',40

select * from #T a
where a.id=(select MIN(id) from #T b where a.name=b.name)
/*
nameidcountx
----------------------------
A         120
B         130
C         140
*/

[解决办法]
SELECT * 
FROM #T AS t1 
WHERE NOT EXISTS(SELECT 1 FROM #T AS t2 WHERE t1.name = t2.name AND t1.id > t2.id)

name       id   countx
---------- ---- -----------
A          1    20
B          1    30
C          1    40

[解决办法]
select * from #T a
where a.id=(select MIN(id) from #T b where a.name=b.name)

热点排行