将公共父/子列拆分为多个列

问题描述 投票:0回答:1

代码/示例数据:

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
不正确):

sql sql-server tsql sql-server-2016
1个回答
1
投票

您不需要所有连接。大部分工作已在前 4 列中为您完成。你只需要用一点知识来连接一些东西,即“任何东西”+ NULL = NULL。

这是使用您良好的测试数据的编码解决方案......

 SELECT  PKey
        ,CKey
        ,GCKey
        ,PCode  = PKey
        ,CCode  = ISNULL(PKey+NULLIF(CKey ,''),'')
        ,GCCODE = ISNULL(PKey+NULLIF(GCKey,''),'')
  FROM @Table
;

...这是该代码的结果。

© www.soinside.com 2019 - 2024. All rights reserved.