编辑:我在发票表中带有transactionId时出错了
我有3张桌子:
Transactions Reconciliations Invoices
id num line transId id Code transId
-- --- ---- ------- -- ---- -------------
3 1 1 3 5 Code 5 3
6 1 2 6 9 Code 9 8
7 1 3 7 12 Code 12 11
8 2 1 8
12 2 2 12
10 3 1 10
11 3 2 11
和此查询:
select
t1.id -- transaction id
t2.num -- reconciliation number
t3.Code -- Invoice code
from Transactions t1
left outer join Reconciliations t2 on t2.transId = t1.id
left outer join Invoices t3 on t3.transId = t1.id
给出以下结果:
id num code
-- --- ----
3 1 Code 5
6 1 null
7 1 null
8 2 Code 9
12 2 null
10 3 null
11 3 Code 12
但我想要的是:
id num code
-- --- ----
3 1 Code 5
6 1 Code 5
7 1 Code 5
8 2 Code 9
12 2 Code 9
10 3 Code 12
11 3 Code 12
当链接的发票表给出null时,要在其上放置单词,我想加入来自具有相同对帐号的对帐的所有记录。
修改:我希望发票中的代码在所有共享相同对帐号码的交易中共享
我试过通过外部应用和子查询,但我无法找到实现它的方法。你知道吗?
答案 0 :(得分:1)
您似乎希望将InvoiceId
中的Transactions
传播到下一个值。
这是一种方法:
select t.*
(select top 1 InvoiceId
from Transactions t2
where t2.id <= t.id and t2.InvoiceId is not NULL
order by id desc
) as newInvoiceId
from transactions t;
然后,您可以将其替换为您的查询:
select
t1.id -- transaction id
t2.num -- reconciliation number
t3.Code -- Invoice code
from (select t.*
(select top 1 InvoiceId
from Transactions t2
where t2.id <= t.id and t2.InvoiceId is not NULL
order by id desc
) as newInvoiceId
from transactions t
) t1
left outer join Reconciliations t2 on t2.transid = t1.id
left outer join Invoices t3 on t3.id = t1.transid ;
答案 1 :(得分:1)
解决方案是在加入Reconciliations
之前再次加入Invoices
:
select t.id, r.num, i.Code
from Transactions t
join Reconciliations r on r.transId = t.id
join Reconciliations r2 on r2.num = r.num
join Invoices i on i.transId = r2.transId
请注意,联接现在是内部连接(要求匹配),以及如何通过共享Reconciliation.num
轻松连接到正确的发票value - 使用内部联接意味着您只能获得匹配的发票行。
要查看此查询的实际效果,请execute it on SQLFiddle
使用左连接到发票,但是您需要一个由max()
组成的组来限制每个事务只有一个发票(没有max()
您将获得许多额外的行与空代码):
select t.id, r.num, max(i.Code) as Code
from Transactions t
join Reconciliations r on r.transId = t.id
join Reconciliations r2 on r2.num = r.num
left join Invoices i on i.transId = r2.transId
group by t.id, r.num
要查看此查询的实际操作,我从上面的小提琴中使发票12无效,execute it on SQLFiddle