高分问个sql语句
是取3条A的记录3条B的3条C的记录
如果不满足3那取最多的记录.根据id倒序取.id是自增的。
filed1里面的内容是不确定的.有可能是d,e,f,g
ID filed1
1 A
2 B
3 C
4 A
5 B
6 A
7 C
8 C
9 C
10 C
11 A
12 A
13 B
得到结果
1 A
2 B
3 C
4 A
5 B
6 A
7 C
13 B
[解决办法]
樓主結果好象不正確?少了一個C,這裡只有兩個.
[解决办法]
if object_id( 'pubs..tb ') is not null
drop table tb
go
create table tb(ID int, filed1 varchar(10))
insert into tb(ID,filed1) values(1 , 'A ')
insert into tb(ID,filed1) values(2 , 'B ')
insert into tb(ID,filed1) values(3 , 'C ')
insert into tb(ID,filed1) values(4 , 'A ')
insert into tb(ID,filed1) values(5 , 'B ')
insert into tb(ID,filed1) values(6 , 'A ')
insert into tb(ID,filed1) values(7 , 'C ')
insert into tb(ID,filed1) values(8 , 'C ')
insert into tb(ID,filed1) values(9 , 'C ')
insert into tb(ID,filed1) values(10, 'C ')
insert into tb(ID,filed1) values(11, 'A ')
insert into tb(ID,filed1) values(12, 'A ')
insert into tb(ID,filed1) values(13, 'B ')
go
select id,filed1 from tb a where id in (select top 3 id from tb b where a.filed1=b.filed1 order by b.id desc)
order by filed1 , id desc
drop table tb
/*
id filed1
----------- ----------
12 A
11 A
6 A
13 B
5 B
2 B
10 C
9 C
8 C
(所影响的行数为 9 行)
*/
[解决办法]
--用子查询
select id,filed1
from 表名 as a
where id in (select top 3 id from 表名 where filed1=a.filed1 order by id desc)
order by filed1 , id desc