0

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

我正在使用一个 IBM 系统,该系统将评论保存在 25 个字符的文本块中。我正在尝试为每个保存的评论重新组合前三段文本块。注释表有注释头号(COMM_NO)、行序号(LINE_SQ)和实际文本(TXT)。我正在查看三个示例评论。评论 #1140 说“保修期满后客户产品退货。需要报价。” 注释 #1408 是两个部分,“更新后尝试呼叫客户”。注释 #2884 很短,仅显示“RMA #467”。表数据如下所示[编辑:更正插入语句]:

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}

我有几次尝试使用别名将表在其自身上 LEFT JOINing 两次。我还没有完全到那里,但这是我迄今为止最接近的尝试:

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

任何帮助表示赞赏。谢谢!

4

1 回答 1

1

首先,在提供 DDL 和 INSERT 语句方面做得很好。您遇到的主要问题是您的 JOIN 定义中的表顺序。连接的顺序很重要OUTERLEFT由于您要针对发出联接,因此在您的声明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
于 2018-11-07T18:23:30.820 回答