我有两个表:第一个是父表,第二个是子表。我想从子表中选择所有父ID的2条记录。
如何选择每个父母的唯一2条记录。
example :
parent table
parent_id group_name
1 first
2 second
child table
child_id parent_id name
1 1 'test1'
2 2 'test2'
3 1 'test3'
我已经尝试过声明,但我发现只有一行来自所有父ID
答案 0 :(得分:0)
WITH cte AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY p.parent_Id ORDER BY c.name DESC) AS rn,c.child_id, p.group_name,c.name
FROM parent as p join child as c on p.parent_Id=c.parent_id
)
SELECT *
FROM cte
WHERE rn <3