繁体   English   中英

(SQL) 如何将两列合并在一起以创建一个新列,然后将该表连接到另一个具有该新列共同的表

[英](SQL) how to merge two columns together to create a new column and then join that table to another table which has that new column in common

我想将 Table_1 中的两列合并在一起(即 column_A 和 column_b 并在列之间添加“|”),这将形成另一列 column_c。 然后我想将 Table_1 中的 column_c 与 Table_2 中的 column_c 组合/连接起来。 这两个表分别有不同的列,我想返回所有数据 - 只有 column_c 是公共列。

我设法通过使用合并两列

Select (column_a + '|' + column_b) as column_c from Table_1

但是我无法将它与 table_2 中的 column_c 连接起来。

因此,查询 [select broker,account,trade_id,currency from transactions where trade_id = '45435'] 将返回以下内容:

经纪商账户 trade_id 货币 HSBC G-HG4_5 45435 EUR

和查询 [select * from summary where code like 'G-HG4_5&'] 将返回

start_date end_date 代码描述经纪商类型 25/05/2015 14/02/2015 G-HG4_5|EUR LONG BARCLAYS

我基本上想结合帐户和货币,使其看起来像第二个表中的“代码”列。 一旦合并,我想把它全部放在一张表中,我可以在那里比较数据。

您可以通过使用 + 运算符或 Concat 运算符连接来直接在 JOIN 中使用合并列,如下所示:请尝试以下操作:

SELECT t1.column_a, t2.column_b, t2.column_c -- add either * or columns list of your choice here
FROM TABLE_2 t2
INNER JOIN t1 ON  t2.column_c = (ISNULL(t1.column_a, '') + '|' + ISNULL(t1.column_b, '')) -- t2.column_c = concat(t1.column_a, '|', t1.column_b)

旁注:如果您使用 + 加入,那么您将需要显式处理 NULL 值检查,因为以下内容将不会执行:

SELECT null + '|' + 'fun';
SELECT 'fun' + '|' + null;

这听起来像你想要做的:

SELECT * 
FROM TABLE_2 t2
INNER JOIN 
    (Select *, (column_a + '|' + column_b) as column_c from Table_1) t1
    ON t1.column_c = t2.column_c

您可以直接在连接条件中使用连接:

SELECT a.*
FROM Table_1 a
INNER JOIN table_2 b
   ON CONCAT(a.column_a,'|',a.column_b)=b.column_c

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM