【问题标题】:Creating a result set of data using data from one table joining on another table containing two key columns使用来自一个表的数据连接到另一个包含两个键列的表来创建数据的结果集
【发布时间】:2019-05-02 21:36:43
【问题描述】:

我正在尝试创建一个合并两个表的汇总结果集。

第一个表(主行和多行)包含以下列:

trans_id, trans_type_id

第二个表(仅一行)包含:

from_trans_type_id, to_trans_type_id

我正在尝试加入这两个表,以便 from_trans_type_id = trans_type_idto_trans_type_id = trans_type_id 并获得相关的 trans_id

我尝试了自联接和派生联接,但没有任何效果。

最终结果是我希望得到一个看起来像这样的结果集:

trans_id as from_trans_id, from_trans_type_id, trans_id as to_trans_id, to_trans_type_id

数据是:

【问题讨论】:

  • 请提供样本数据。但是,根据您的问题,我认为没有满足条件 from_trans_type_id = trans_type_id 和 to_trans_type_id = trans_type_id 的记录。除此之外,我认为您的逻辑没有其他问题
  • 我添加了一些示例数据

标签: sql sql-server


【解决方案1】:

您可以将 join 与 firsttable 的多个实例一起使用

select b.trans_id as from_trans_id, from_trans_type_id, c.trans_id as to_trans_id, to_trans_type_id 
from secondtable a 
inner join firsttable b on a.from_trans_type_id=b.trans_type_id
inner join firsttable c on a.to_trans_type_id=c.trans_type_id

【讨论】:

    猜你喜欢
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    相关资源
    最近更新 更多