求一SQL,关于有条件消除重复列,表结构很简单,就两列,内容里有具体要求,谢谢~~~~~

哈哈哈哈 2008-03-22 04:29:12
表table结构如下:

id name
1 a1
2 a1
3 a1
4 a1
5 a2
6 a2
7 a3

需要如下结果
id name
1 a1
2 a1
3 a1
5 a2
6 a2
7 a3
其实就是需要重复列name中前三条记录,超过三条取前三条,没超过三条都取~~~~~

谢谢~!!!!
...全文
84 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
bqb 2008-03-22
  • 打赏
  • 举报
回复
create table tb(id int,name varchar(10))
insert into tb
select 1,'a1' union all
select 2,'a1' union all
select 3,'a1' union all
select 4,'a1' union all
select 5,'a2' union all
select 6,'a2' union all
select 7,'a3'

select id,name
from tb a
where (select count(1) as num from tb where name=a.name and id<=a.id)<4
/*
id name
---------------
1 a1
2 a1
3 a1
5 a2
6 a2
7 a3
*/



drop table tb
Limpire 2008-03-22
  • 打赏
  • 举报
回复
--> 测试数据: #
if object_id('tempdb.dbo.#') is not null drop table #
create table # (id int,name varchar(2))
insert into #
select 1,'a1' union all
select 2,'a1' union all
select 3,'a1' union all
select 4,'a1' union all
select 5,'a2' union all
select 6,'a2' union all
select 7,'a3'

select * from # a where id in (select top 3 id from # where name = a.name order by 1)
/*
id name
1 a1
2 a1
3 a1
5 a2
6 a2
7 a3
*/

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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