高手请进,比较复杂

casper1 2009-03-27 03:00:09
TABLE1:
ID MC AGE
1 A 5
2 A 7
3 A 8
4 A 5
5 B 1
6 B 3
7 C 4
8 C 3
9 C 3
通过select * from table t where age=(select min(age) from table where MC=t.MC ) 得到下面的结果(得到字段AGE(按MC分组)的最小值的记录):
ID MC AGE
1 a 5
4 a 5
5 b 1
8 c 3
9 c 3
那要再通过怎么样才能得到下面的结果:(上面的结果集中取ID小的记录)
ID MC AGE
1 A 5
4 B 1
7 C 3
...全文
42 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2009-03-27
  • 打赏
  • 举报
回复
create TABLE tb(ID INT,MC VARCHAR(1),AGE INT)
INSERT tb
SELECT 1, 'A', 5 UNION ALL
SELECT 2, 'A', 7 UNION ALL
SELECT 3, 'A', 8 UNION ALL
SELECT 4, 'A', 5 UNION ALL
SELECT 5, 'B', 1 UNION ALL
SELECT 6, 'B', 3 UNION ALL
SELECT 7, 'C', 4 UNION ALL
SELECT 8, 'C', 3 UNION ALL
SELECT 9, 'C', 3

select ID ,MC, AGE from
(
select *, px = (select count(1) from tb where mc = t.mc and (age < t.age or (age=t.age and id < t.id))) + 1 from tb t
) m
where px = 1
order by mc

drop table tb

/*
ID MC AGE
----------- ---- -----------
1 A 5
5 B 1
8 C 3

(所影响的行数为 3 行)
*/
dawugui 2009-03-27
  • 打赏
  • 举报
回复
select ID ,MC, AGE from
(
select *, px = (select count(1) from tb where mc = t.mc and (age < t.age or (age=t.age and id < t.id))) + 1 from tb t
) m
where px = 1
order by mc
sdhdy 2009-03-27
  • 打赏
  • 举报
回复
select * from table1 a where not exists(select 1 from table1 where  MC=a.MC and id<a.id)
playwarcraft 2009-03-27
  • 打赏
  • 举报
回复

Create table T (ID INT,MC VARCHAR(1),AGE INT)
INSERT T
SELECT 1, 'A', 5 UNION ALL
SELECT 2, 'A', 7 UNION ALL
SELECT 3, 'A', 8 UNION ALL
SELECT 4, 'A', 5 UNION ALL
SELECT 5, 'B', 1 UNION ALL
SELECT 6, 'B', 3 UNION ALL
SELECT 7, 'C', 4 UNION ALL
SELECT 8, 'C', 3 UNION ALL
SELECT 9, 'C', 3
Go
select min(A.id) as ID,A.mc,A.age
from T A
inner join
(
select mc,min(age) as age
from t
group by mc
) B
on A.mc=B.mc and A.age=B.age
group by A.mc,A.age
/*
id mc age
-----------------------
1 A 5
5 B 1
8 C 3

*/
GO
drop table T
playwarcraft 2009-03-27
  • 打赏
  • 举报
回复
select min(A.id) as ID,A.mc,A.age
from T A
inner join
(
select mc,min(age) as age
from t
group by mc
) B
on A.mc=B.mc and A.age=B.age
group by A.mc,A.age
csdyyr 2009-03-27
  • 打赏
  • 举报
回复
DECLARE @TB TABLE(ID INT,MC VARCHAR(1),AGE INT)
INSERT @TB
SELECT 1, 'A', 5 UNION ALL
SELECT 2, 'A', 7 UNION ALL
SELECT 3, 'A', 8 UNION ALL
SELECT 4, 'A', 5 UNION ALL
SELECT 5, 'B', 1 UNION ALL
SELECT 6, 'B', 3 UNION ALL
SELECT 7, 'C', 4 UNION ALL
SELECT 8, 'C', 3 UNION ALL
SELECT 9, 'C', 3


SELECT * FROM @TB AS A WHERE NOT EXISTS(SELECT 1 FROM @TB WHERE MC=A.MC AND ID<A.ID)
/*
ID MC AGE
----------- ---- -----------
1 A 5
5 B 1
7 C 4
*/

22,219

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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