主表带动副表一起分页

相关贴子: https://bbs.csdn.net/topics/392447008 

use tempdb
go
IF Object_ID('mainT') is not null drop table mainT
IF Object_ID('subT') is not null drop table subT
go
CREATE TABLE mainT(
	id INT IDENTITY(1,1) PRIMARY KEY,
	n NVARCHAR(10)	
)
GO
CREATE TABLE subT(
	subId INT IDENTITY(1,1) PRIMARY KEY,
	id INT,
	subN NVARCHAR(10)	
)
GO
INSERT INTO mainT(n) VALUES('a'),('b'),('c'),('d'),('e')
INSERT INTO subT(id,subN) VALUES(1,'aa'),(1,'bb'),(2,'cc'),(2,'dd'),(3,'ee'),(3,'ff'),(3,'gg'),(4,'gg'),(4,'hh'),(5,'ii')
GO
DECLARE @pageIndex INT,@pageSize INT
SET @pageIndex=2
SET @pageSize=2

;WITH cte AS (
	SELECT ROW_NUMBER() OVER (ORDER BY id) AS rid,* FROM mainT
),cte2 AS (
SELECT ROW_NUMBER() OVER (PARTITION BY a.rid ORDER BY b.subN) AS rid2,a.*,b.subId,b.subN 
FROM cte AS a LEFT JOIN subT AS b 
	ON a.id=b.id 
WHERE a.rid > (@pageIndex-1)*@pageSize AND a.rid<=@pageIndex*@pageSize
)
SELECT 
t.id
,CASE WHEN rid2=1 THEN LTRIM(t.n) ELSE '' END AS n
,t.subId
,t.subN
FROM cte2 AS t
ORDER BY t.rid,t.rid2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值