如何加入选择顶部

时间:2018-10-08 07:47:35

标签: sql sql-server tsql

我对多个表的组合有疑问。 我的SQL查询:

SELECT *
FROM CRM.Bank as a
JOIN CRM.Documents as b ON a.Bank_ID = b.Documents_ID
JOIN CRM.Counterparties as c ON c.Counterparties_ID = b.Documents_ID
JOIN CRM.Items as d ON d.Document_tran_ID = b.Documents_ID 

我有表CRM.Items,该表具有以下列:

Item_ID     Document_tran_ID    Name
=======     ================    ====
1           1                   Advertising banner
2           1                   Shipping costs
3           2                   Garden tent
4           2                   Additional fasteners
5           2                   Shipping costs

现在我有一个问题,如何仅将第一个项目连接到文档(d.Document_tran_ID = b.Documents_ID)? 我知道我应该使用SELECT TOP。但是,我在创建正确的查询时遇到了问题

以以下形式期待结果

Bank_ID     Documents_ID        Counterparties_ID       Document_tran_ID    Name
=======     ============        =================       ================    ====
22          1                   4                       1                   Advertising banner
23          2                   20                      2                   Garden tent
24          3                   21                      3                   Other

仅匹配文档中的第一个项目。

2 个答案:

答案 0 :(得分:4)

我认为您可以尝试使用 CROSS APPLY 联接。在内部查询中,您可以应用订单条件以选择 TOP

SELECT *
FROM CRM.Bank as a
JOIN CRM.Documents as b ON a.Bank_ID = b.Documents_ID
JOIN CRM.Counterparties as c ON c.Counterparties_ID = b.Documents_ID
CROSS APPLY
  (select top 1 * from CRM.Items i where  i.Document_tran_ID = b.Documents_ID) as d

答案 1 :(得分:0)

对文档表使用子查询

SELECT *
FROM CRM.Bank as a
JOIN ( select min(Document_tran_ID) as Documents_ID from CRM.Documents) as b ON a.Bank_ID = b.Documents_ID
JOIN CRM.Counterparties as c ON c.Counterparties_ID = b.Documents_ID
JOIN CRM.Items as d ON d.Document_tran_ID = b.Documents_ID