在同一个表上双击LEFT JOIN进行Transpose



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}

我在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是这样的null:

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

感谢您的帮助。谢谢

首先,在提供DDL和INSERT语句方面做得很好。您遇到的主要问题是JOIN定义中的表顺序。OUTER联接上的订单事项。由于您要针对comm1发出LEFT联接,因此这始终需要放在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

注意-我还在WHERE子句中放入了comm1.LINE_SQ = 1条件,这样您就不必在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

相关内容

  • 没有找到相关文章

最新更新