需要帮助来查找父子组合的输出

时间:2016-05-04 17:37:02

标签: sql sql-server tsql sql-server-2012

样本记录:

DECLARE @Temp TABLE (
    ID INT,
    Child VARCHAR(5),
    Parent VARCHAR(5),
    Comment VARCHAR(5)
)
INSERT @Temp VALUES
(1, 'C1', 'P1', 'AA'),
(1, 'C2', 'P2', ''  ),
(1, 'C3', 'P3', 'XX'),
(1, 'C4', 'P4', 'YY'),
(1, 'C5', 'P5', ''  ),
(1, 'C6', 'P6', 'ZZ'),
(1, 'C7', 'P7', ''  ),
(1, 'C8', 'P8', ''  ),
(1, 'C9', 'P9', 'TT'),
(1, 'C10','P10','')

源表的记录看起来像上面的@temp表的记录。 我们可以设计一个TSQL脚本,它可以使用@temp作为源表,并且该脚本可以像下面的结果表一样给出输出。

如果父子组合的注释值为NULL /空,则下一个后续的NOT NULL /非空注释需要替换。

输出我需要的是这样的

ID  Child   Parent  [Comment]
1   C1      P1      AA 
1   C2      P3      XX  
1   C3      P3      XX  
1   C4      P4      YY  
1   C5      P6      ZZ  
1   C6      P6      ZZ  
1   C7      P9      TT  
1   C8      P9      TT  
1   C9      P9      TT  
1   C10     P10     

任何形式的帮助都将受到高度赞赏! 感谢

2 个答案:

答案 0 :(得分:2)

您可以使用OUTER APPLY执行您想要的操作,以获取下一个有效的ParentID及其评论。

SELECT  ID,
        Child,
        CASE WHEN t1.Comment = '' THEN NextParent ELSE Parent END AS Parent,
        CASE WHEN t1.Comment = '' THEN NextComment ELSE Comment END AS Comment
FROM @Temp t1 
OUTER APPLY (SELECT TOP 1 t2.Parent [NextParent], t2.Comment [NextComment]
             FROM @Temp t2 
             WHERE t2.Parent > t1.Parent AND t2.Comment <> ''
             ORDER BY t2.Parent) ca

最后一个值P10将是不正确的,因为您必须操纵这些类型的值才能正确排序,因为P10介于P1和P2之间

答案 1 :(得分:1)

借助递归cte:

;WITH cte AS (
SELECT ID, Child, Parent, Comment
FROM @Temp
UNION ALL
SELECT t.ID, t.Child, c.Parent, c.Comment
FROM cte c
INNER JOIN @Temp t 
    ON CAST(STUFF(c.Child,1,1,'') as int) = CAST(STUFF(t.Child,1,1,'') as int)+1
WHERE t.comment = ''
)

SELECT  MAX(ID) as ID,
        Child,
        MAX(Parent) as Parent,
        MAX(Comment) as Comment
FROM cte
GROUP BY Child
ORDER BY CAST(STUFF(Child,1,1,'') as int)

输出:

ID          Child Parent Comment
----------- ----- ------ -------
1           C1    P1     AA
1           C2    P3     XX
1           C3    P3     XX
1           C4    P4     YY
1           C5    P6     ZZ
1           C6    P6     ZZ
1           C7    P9     TT
1           C8    P9     TT
1           C9    P9     TT
1           C10   P10    

(10 row(s) affected)