mssql父子查找sql

时间:2016-01-13 23:24:31

标签: sql-server parent-child

所以我在这里有一张与此类似的表http://sqlfiddle.com/#!9/ea557/1 这是较大的复杂sql的一小部分。我想要的东西需要像

ParentId | TopChildId | AllChild     | Priority
--------------------------------------------
  10     |   541      | 345, 541     | 2
  12     |   125      | 123, 124,125 | 3
  13     |   103      | 103, 104     | 2
  14     |   161      | 161          | 1

我希望这是有道理的。因此,在一行中,我希望看到父ID,具有最大优先级编号的子ID,并在列中列出所有子ID的连接。

感谢您的任何帮助。

2 个答案:

答案 0 :(得分:0)

要获得带有CID的{​​{1}} priority,您可以使用ROW_NUMBER。要获取每个CID的连结PID,您可以使用FOR XML PATH

SQL Fiddle

WITH Cte AS(
    SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY PID ORDER BY priority DESC)
    FROM ParChi
)
SELECT
    ParentID = c.PID,
    TopChildId = c.CID,
    x.AllChild,
    c.priority
FROM Cte c
CROSS APPLY(
    SELECT STUFF((
        SELECT ', ' + CONVERT(VARCHAR(10), CID)
        FROM ParChi
        WHERE PID = c.PID
        ORDER BY priority
        FOR XML PATH('')
    ),1, 2, '') AS AllChild
) x
WHERE rn = 1
ORDER BY ParentID

答案 1 :(得分:0)

SELECT p.PID AS ParentId , MAX(p.CID) AS TopChildId, temp.AllChild, MAX(p.priority) 
FROM ParChi p
OUTER APPLY
(
    SELECT 
    STUFF((SELECT ', ' +  pc.CID 
    FROM ParChi pc          
    WHERE pc.PID = p.PID
    FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 0, '') AS AllChild   
)AS temp
GROUP BY p.PID ORDER BY p.PID