首页 > 解决方案 > Transact SQL - 将一张表与其他两张表连接起来

问题描述

我有一个用于 PaymentRequest (PR) 的表,每个 PR 表都有两种支付形式,一个 WorkProgress 和一个 AdvanceByWarranty,关系是这样的:

数据模型

我需要创建一个报告以获取该 (PR) 中的所有付款,以及它们之间的其他一些字段

我用来将 PaymentRequest 与 WorkProgress 连接的 sql 是这样的,它可以工作,它返回该付款的 WorkProgress

工作进度

为了通过保修获得预付款,我使用它,它也有效,返回 2 预付款,因为它应该是

提前保修

但是,当我将两者混合时,它不会返回 3 行,它应该返回 2 行。结果是这样的

两个都

我期待这样的事情(名字更短)

预期查询

我怎样才能得到预期的查询?

编辑:

获取预期查询的 sql 是这样的

select 
pr.ProjectId, pr.NumberPaymentState, 
wp.ToCollectAmmount as WPAmmount, wp.ToCollectPercent as WPPercent,
null as AWAmmount, null as AWPercent
from PaymentRequests pr
left join WorkProgresses wp on (wp.ProjectId = pr.ProjectId and wp.NumberPaymentState = pr.NumberPaymentState)

union all

select 
pr.ProjectId, pr.NumberPaymentState, 
null as WPAmmount, null as WPPercent,
aw.ToCollectAmmount as AWAmmount, aw.ToCollectPercent as AWPercent
from PaymentRequests pr
left join AdvanceByWarranties aw on (aw.ProjectId = pr.ProjectId and aw.NumberPaymentState = pr.NumberPaymentState)

标签: sqlsql-servertsql

解决方案


你可能想要你展示的东西,但它不是这样工作的。

只需UNION ALL在前两个查询之间使用,并相应地重命名列。这里有一些伪代码混合来指导你:

select keycols, workercols, null as advancecols
from pr join worker

union all

select keycols, null as workercols, advancecols
from pr join advancecols

推荐阅读