求教一个sql 查询

zlb789 2009-03-11 11:44:00
表 A
a b c
1 sf t1
2 s t1
3 dd t2
4 dd t3
6 dd t6


现在想一次查询出,每个c类的前2条 , 就是2个t1 ,2个t2 ,.这样的记录 ,c的类别不确定
如果类别确定可以用union 但是类别不确定 如果写?
...全文
100 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
wuyq11 2009-03-11
  • 打赏
  • 举报
回复
在存储过程里通过
insert into #ls select distinct(c) from A
对#ls使用游标也可
CutBug 2009-03-11
  • 打赏
  • 举报
回复
declare @A table(a int,  b varchar(2), c nchar(2))
insert into @A
select 1 ,'sf','t1' union all
select 2 ,'s','t1' union all
select 3 ,'dd','t2' union all
select 4 ,'dd','t3' union all
select 6 ,'dd','t6' union all
select 7 ,'dd','t2'

select top 4 * from @A where c in
(select top 2 c from @A group by c)

a b c
----------- ---- ----
1 sf t1
2 s t1
3 dd t2
7 dd t2

(4 行受影响)
zzxap 2009-03-11
  • 打赏
  • 举报
回复
select top 4 * from @A where c in
(select top 2 c from @A group by c)
zlb789 2009-03-11
  • 打赏
  • 举报
回复
谢谢
结帖给分
nj_1st_excellence 2009-03-11
  • 打赏
  • 举报
回复
create table tb
(
a int,
b nvarchar(50),
c nvarchar(50),
)
insert tb select 1,'sf','t1'
insert tb select 2,'s','t1'
insert tb select 3,'dd','t2'
insert tb select 4,'dd','t3'
insert tb select 6,'dd','t6'


select * from tb t where a in
(select top 2 a from tb where c=t.c)

drop table tb



(1 個資料列受到影響)

(1 個資料列受到影響)

(1 個資料列受到影響)

(1 個資料列受到影響)

(1 個資料列受到影響)
a b c
----------- -------------------------------------------------- --------------------------------------------------
1 sf t1
2 s t1
3 dd t2
4 dd t3
6 dd t6

(5 個資料列受到影響)


CutBug 2009-03-11
  • 打赏
  • 举报
回复
declare @A table(a int,  b varchar(2), c nchar(2))
insert into @A
select 1 ,'sf','t1' union all
select 2 ,'s','t1' union all
select 3 ,'dd','t2' union all
select 4 ,'dd','t3' union all
select 6 ,'dd','t6' union all
select 7 ,'dd','t2' union all
select 8 ,'cc','t1' union all
select 9 ,'a','t2' union all
select 10 ,'s','t2'

select * from @A m where a in
(select top 2 a from @A where c=m.c)
order by m.c
a b c
----------- ---- ----
1 sf t1
2 s t1
3 dd t2
7 dd t2
4 dd t3
6 dd t6

(6 行受影响)

62,267

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

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