在同一张桌子上进行双左联接以进行转置

时间:2018-11-07 18:03:29

标签: sql left-join transpose orphan

IBM iNavigator(或通用/不可知的SQL):

我正在使用一个IBM系统,该系统将注释保存在25个字符的文本块中。我正在尝试为每个保存的注释重新组合文本块的前三个部分。注释表具有注释标题号(COMM_NO),行序号(LINE_SQ)和实际文本(TXT)。我正在看三个示例注释。注释#1140说:“保修到期后返回客户产品。需要发出报价。”注释#1408有两个部分,“尝试在更新后致电客户”。评论2884简短,仅显示“ RMA#467”。表数据如下所示:[EDIT:更正后的插入语句]:

CREATE TABLE mycomments
    ([COMM_NO] int, [LINE_SQ] int, [TXT] varchar(25))
;
INSERT INTO mycomments
    ([COMM_NO], [LINE_SQ], [TXT])
VALUES
    (1140, 1, 'Customer product return a'),
    (1140, 2, 'fter warranty expired. Ne'),
    (1140, 3, 'eds quote issued.'),
    (1408, 1, 'Tried to call customer af'),
    (1408, 2, 'ter update.'),
    (2884, 1, 'RMA #467');

我需要的是这个

COMM_NO  TXT1                      TXT2                      TXT3
-------  ------------------------- ------------------------- ------------------------- 
1140     Customer product return a fter warranty expired. Ne eds quote issued.
1408     Tried to call customer af ter update.               {null} 
2884     RMA #467                  {null}                    {null}

我多次尝试使用别名对表本身进行两次联接。我还没有完全到那儿,但这是我到目前为止最接近的尝试:

SELECT 
  comm1.COMM_NO
, comm1.TXT as TXT1
, comm2.TXT as TXT2
, comm3.TXT as TXT3
  FROM mycomments comm1
  LEFT JOIN mycomments AS comm2 ON comm2.COMM_NO = comm1.COMM_NO AND comm1.LINE_SQ=1 AND comm2.LINE_SQ=2
  LEFT JOIN mycomments AS comm3 ON comm3.COMM_NO = comm1.COMM_NO AND comm1.LINE_SQ=1 AND comm2.LINE_SQ=2 AND comm3.LINE_SQ=3

实际上,即使上面的TXT3或TXT2 / TXT3为空,我也确实想将这三个段合并在一起:

COMM_NO  BIGTXT1
-------  --------------------------------------------------------------------------- 
1140     Customer product return after warranty expired. Needs quote issued.
1408     Tried to call customer after update.
2884     RMA #467

感谢您的帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

首先,在提供DDL和INSERT语句方面做得很好。您遇到的主要问题是JOIN定义上的表顺序。 OUTER个联接上的顺序事项。由于您要针对LEFT发出comm1联接,因此始终需要在ON语句中排在第一位。换句话说,您说的是“总是从comm1中给我数据,并且如果有数据,就给我联接表中的任何东西。”因此,我将其重写为:

SELECT 
  comm1.COMM_NO
, comm1.TXT as TXT1
, comm2.TXT as TXT2
, comm3.TXT as TXT3
  FROM mycomments comm1
  LEFT JOIN mycomments AS comm2 ON comm1.COMM_NO = comm2.COMM_NO AND comm2.LINE_SQ=2
  LEFT JOIN mycomments AS comm3 ON comm1.COMM_NO = comm3.COMM_NO AND comm3.LINE_SQ=3
  WHERE comm1.LINE_SQ = 1

注意-我还将comm1.LINE_SQ = 1条件放在WHERE子句中,因此您不必在JOIN上重复它。我使用您提供的DDL进行了测试,它可以按预期工作。

如果您想在一个大列中,可以对SELECT语句执行以下操作:

comm1.TXT + CASE WHEN comm2.TXT IS NOT NULL THEN comm2.TXT ELSE '' END + CASE WHEN comm3.TXT IS NOT NULL THEN comm3.TXT ELSE '' END BIGTXT1