SQL Join,在单独的行中显示每个表的结果

时间:2018-10-22 15:14:40

标签: sql sql-server

我需要能够从发票中选择每一行并显示在单独的行中。有两种类型的线,普通线和自定义线。

为澄清起见,每个预订都有一个拥有多个产品预订的购物车预订,每个产品预订只能有一个发票,该发票可以同时包含多个常规(BokunProductInvoiceLine)行和自定义行。

代码如下:

Select 
CB.ConfirmationCode as 'Confirmation Code',
PB.ProductConfirmationCode as 'Product ConfirmationCode',
BPL.[Title] as 'Normal line title',
BPL.[CostGroupTitle] as 'Normal line title',
CL.Title as 'Custom line title'

From [dbo].[BokunProductBooking] PB
Join [dbo].[BokunCartBooking] CB
On Pb.ParentBookingId = CB.Id
Join [dbo].[BokunInvoice] BI
On Bi.BookingId = PB.Id  AND BI.Active = 1
left Join BokunCustomLine CL
On CL.InvoiceId = BI.Id
FULL JOIN BokunProductInvoiceLine BPL
On BPL.ProductInvoiceId = BI.Id

这是我通过此查询得到的结果: enter image description here

这是我想要得到的结果: enter image description here

谢谢:)

1 个答案:

答案 0 :(得分:1)

听起来像是“联盟”的工作,但是“全部联盟”会让您更快到达那里。

Select 
CB.ConfirmationCode as [Confirmation Code],
PB.ProductConfirmationCode as [Product ConfirmationCode],
BPL.[Title],
BPL.[CostGroupTitle] as [Cost Group title],
cast(null as varchar(max)) as [Custom line title]
From [dbo].[BokunProductBooking] PB
Join [dbo].[BokunCartBooking] CB On Pb.ParentBookingId = CB.Id
Join [dbo].[BokunInvoice] BI On Bi.BookingId = PB.Id  AND BI.Active = 1
Join BokunProductInvoiceLine BPL On BPL.ProductInvoiceId = BI.Id

union all

Select 
CB.ConfirmationCode,
PB.ProductConfirmationCode,
NULL,
NULL,
CL.Title
From [dbo].[BokunProductBooking] PB
Join [dbo].[BokunCartBooking] CB On Pb.ParentBookingId = CB.Id
Join [dbo].[BokunInvoice] BI On Bi.BookingId = PB.Id  AND BI.Active = 1
Join BokunCustomLine CL On CL.InvoiceId = BI.Id