代码/示例数据:
DECLARE @Table TABLE
(
PKey VARCHAR(10),
CKey VARCHAR(10),
GCKey VARCHAR(10),
CODE VARCHAR(10)
);
INSERT INTO @Table
SELECT 'A','','','A'
UNION ALL
SELECT 'A','AB1','','AAB1'
UNION ALL
SELECT 'A','AB2','','AAB2'
UNION ALL
SELECT 'A','AB2','AB2C1','AAB2C1'
UNION ALL
SELECT 'A','AB3','','AAB3'
UNION
SELECT 'A','AB3','AB3C1','AAB3C1'
UNION
SELECT 'A','AB3','AB3C2','AAB3C2'
UNION
SELECT 'B','','','B'
UNION
SELECT 'B','BB1','','BBB1'
UNION
SELECT 'C','','','C'
UNION
SELECT 'C','CB1','','CCB1'
UNION
SELECT 'C','CB1','CB1C1','CCB1C1'
SELECT * FROM @Table ;
目标:层次结构(只有 3 级)是
PKey
(父键)> CKey
(子键)> GCKey
(孙键)。 Code
是我尝试拆分为 3 个不同列的值(PCode
、CCode
和 GCCOde
)。我想用其 Code
列填充有值的每个父列。
有没有办法在没有 3 个自连接的情况下做到这一点?
预期结果:
我的尝试:
SELECT
[T1].[PKey], [T1].[CKey], [T1].[GCKey],
[T1].[CODE] AS [PCode],
COALESCE ([T2].[CODE], '') AS [CCode],
COALESCE ([T3].[CODE], '') AS [GCCode]
FROM
@Table AS [T1]
LEFT JOIN
@Table AS [T2] ON [T2].[PKey] = [T1].[PKey]
AND [T2].[CKey] = [T1].[CKey]
AND [T2].[CKey] <> ''
AND [T2].[GCKey] = ''
LEFT JOIN
@Table AS [T3] ON [T3].[PKey] = [T1].[PKey]
AND [T3].[CKey] = [T1].[CKey]
AND [T3].[GCKey] <> ''
AND [T3].[GCKey] = [T1].[GCKey] ;
当前输出(注意
PCode
不正确):