22,219
社区成员
发帖
与我相关
我的任务
分享
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 行)
*/
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
select * from table1 a where not exists(select 1 from table1 where MC=a.MC and id<a.id)
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
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
*/