left join 右表条数限制!

s330k 2016-02-26 02:18:45
表A ,id

表B ,id 、aid 、 title

要求得到:
根据A.id=B.aid为条件,获取 相对应的top 2 条数据。

a.id, b.id, b.title
1 2 aaa
1 6 bbb
2 7 cccc
2 11 fffff
3 8 iiiii
3 9 ppppp
...全文
1104 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
dllxf 2016-02-26
  • 打赏
  • 举报
回复
create table a1 (id int) create table a2 (id int, aid int ,title nvarchar(30)) insert into a1 select 1 union all select 2 union all select 3 insert into a2 select 2,1,N'aaaa' union all select 6,1 ,N'bbbb' union all select 7,2, N'cccc' union all select 11,2,N'ffff' union all select 8,3, N'iiii' union all select 9,3, N'pppp' select * from a1 select * from a2 with tab as (select *, rank()over(partition by aid order by id) as sor1 from a2 ) selet aid,id,title,sor1 from tal
中国风 2016-02-26
  • 打赏
  • 举报
回复
select * from A cross apply(select top 2 * from B where aid=a.ID) AS b

22,210

社区成员

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

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