相关贴子: 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