您需要设置一个时间表(如果您不想使用数字表,请参阅下面的替代解决方案):
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
INTO Numbers
FROM sys.columns s1
CROSS JOIN sys.columns s2
ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)
设置 Numbers 表后,使用以下查询:
DECLARE @ParentTable table (ID int,Name varchar(20))
DECLARE @ChildTable table (ID int,ParentID int,Name varchar(20))
INSERT INTO @ParentTable VALUES (1,'Bob')
INSERT INTO @ChildTable VALUES (1,1,'Jim')
INSERT INTO @ChildTable VALUES (2,1,'Ned')
SELECT DISTINCT
dt.Name,c.Name
FROM (SELECT
CASE WHEN n.Number=1 THEN NULL ELSE p.ID END AS ID,p.Name
FROM @ParentTable p
INNER JOIN Numbers n ON 1=1
WHERE p.ID=1 AND n.Number<=2
) dt
LEFT OUTER JOIN @ChildTable c ON dt.ID=c.ParentID
ORDER BY 1,2
输出:
Name Name
-------------------- --------------------
Bob NULL
Bob Jim
Bob Ned
(3 row(s) affected)
如果您不想创建 Numbers 表,则可以使用此方法的替代解决方案,返回与上述相同的输出:
SELECT DISTINCT
dt.Name,c.Name
FROM (SELECT
CASE WHEN n.Number=1 THEN NULL ELSE p.ID END AS ID,p.Name
FROM @ParentTable p
INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY object_id) AS Number FROM sys.columns) n ON n.Number<=2
WHERE p.ID=1 AND n.Number<=2
) dt
LEFT OUTER JOIN @ChildTable c ON dt.ID=c.ParentID
ORDER BY 1,2
我试图使用 A CTE 来扩展父行,但是如果不使用 UNION 就很难!