考虑以下架构:
表格发票:
Id|TotalSum|Status
1|12|1
1|13|0
Table ClientInvoices:
Id|ClientId|InvoiceId
表“发票”可能包含多个具有相同身份但具有不同状态的发票(对身份和状态有唯一约束)。状态是整数,表示枚举(0 - 无效,1 - 有效)
我希望所有客户发票都有价格变动,如果有的话:
ClientId|InvoiceId|SumBefore|SumAfter
如果没有非活动发票,则PreviousPrice应为null。我试图使用以下查询来实现此目的:
SELECT Clients.Id AS ClientId,
Invoice.Id AS InvoiceId,
ActualInvoice.TotalSum AS SumBefore,
InActiveInvoice.TotalSum AS SumAfter
FROM Invoices
LEFT JOIN ClientInvoices AS ActualInvoice ON ActualInvoice.InvoiceId AND Status = 1
LEFT JOIN ClientInvoices AS Inactive ON ActualInvoice.InvoiceId AND Status = 0
LEFT JOIN Clients ON Clients.Id = ClientInvoices.ClientId
如果一张发票有两条记录,则可以正常运行:过去(初始)和当前。但是,如果只有一张发票 - 它具有有效状态,并且使用上面的查询,我会得到SumBefore
= null和SumAfter
=值,该值应位于SumBefore
列中。
如果我可以指定在条件上加入记录,如果该记录的行数为f.e,那将是很好的。这可能吗?
答案 0 :(得分:1)
我认为这应该有效:
select c.ClientId as ClientId,
a.InvoiceId as InvoiceId,
a.TotalSum as SumBefore,
b.TotalSum as SumAfter
from Invoices a left join Invoices b
on a.InvoiceId = b.InvoiceId
and a.status = 1 and b.status = 0
join ClientsInvoices c on c.InvoiceId = a.InvoiceId