I got a child table that contains 1 to n records linked to the m开发者_如何转开发aster table via a MasterID column.
How can I select from the child table only the first 5 records for each MasterID?
Using Sql Server CTE and ROW_NUMBER you could try using
DECLARE @ParentTable TABLE(
ID INT
)
INSERT INTO @ParentTable SELECT 1
INSERT INTO @ParentTable SELECT 2
INSERT INTO @ParentTable SELECT 3
DECLARE @ChildTable TABLE(
ID INT,
ParentID INT
)
INSERT INTO @ChildTable SELECT 1, 1
INSERT INTO @ChildTable SELECT 2, 1
INSERT INTO @ChildTable SELECT 3, 1
INSERT INTO @ChildTable SELECT 4, 1
INSERT INTO @ChildTable SELECT 5, 1
INSERT INTO @ChildTable SELECT 6, 1
INSERT INTO @ChildTable SELECT 7, 1
INSERT INTO @ChildTable SELECT 8, 2
INSERT INTO @ChildTable SELECT 9, 2
INSERT INTO @ChildTable SELECT 10, 3
INSERT INTO @ChildTable SELECT 11, 3
;WITH RowNums AS(
SELECT pt.ID ParentID,
ct.ID ChildID,
ROW_NUMBER() OVER (PARTITION BY pt.ID ORDER BY ct.ID) RowNum
FROM @ParentTable pt INNER JOIN
@ChildTable ct ON pt.ID = ct.ParentID
)
SELECT ParentID,
ChildID
FROM RowNums
WHERE RowNum <= 5
Try a regular join where the constraint is a subquery pulling the TOP 5 from the child table. In untested pseudocode:
SELECT A.MasterID, B.*
FROM MasterTable A
JOIN ChildTable B
ON A.MasterID = B.MasterID
AND B.ChildID IN (SELECT Top 5 ChildID FROM ChildTable
WHERE MasterID = A.MasterID ORDER BY Whatever)
精彩评论