2016-08-15 42 views
0

我正在使用SQL Server,我有兩個表格:InvoiceInvoiceService內部連接沒有來自左表的重複值?

發票

InvoiceID  InvoiceDate  InvoicePrice  InvoicePaidAmount PatientID 
---------------------------------------------------------------------------- 
1    01-01-2016  50     30    1 
2    01-02-2016  100    100    2 

InvoiceService

ID  InvoiceID  ServiceName  ServicePrice 
------------------------------------------------- 
1   1   Dermato    20 
2   1   ophthalmo   30 
3   2   General   100 

我的查詢:

select 
    ServiceName, ServicePrice, InvoiceID, InvoicePrice, 
    InvoicePaidAmount, PatientID 
from 
    InvoiceService 
inner join 
    Invoice on Invoice.InvoiceID = InvoiceService.InvoiceID 

結果:

ServiceName ServicePrice InvoiceID InvoicePrice InvoicePaidAmount PatientID 

Dermato  20   1   50   30    1 
ophthalmo 30   1   50   30    1 
General  100   2   100   100    2 

我需要從左表獲取非重複值: 當發票已經超過1個服務我想要的發票價格和InvoicePaidAmount不重複這樣的例子:

ServiceName ServicePrice InvoiceID InvoicePrice InvoicePaidAmount PatientID 

Dermato  20   1   50   30    1 
ophthalmo 30   1   0    0    1 
General  100   2   100   100    2 
+0

不使用數據庫引擎標記不使用 –

+0

使用左連接和不同的選擇。 http://www.w3schools.com/sql/sql_distinct.asp,http://www.w3schools.com/sql/sql_join_left.asp – tenten

回答

1

如果我理解正確,您希望一個發票服務「真正」匹配。

select s.ServiceName, s.ServicePrice, i.InvoiceID, 
     (case when seqnum = 1 then i.InvoicePrice else 0 end) as InvoicePrice, 
     (case when seqnum = 1 then i.InvoicePaidAmount else 0 end) as InvoicePaidAmount, 
     i.PatientID 
from Invoice i join 
    (select s.*, 
      row_number() over (partition by s.InvoiceID order by s.id) as seqnum 
     from InvoiceService s 
    ) s 
    on i.InvoiceID = s.InvoiceID 
+0

非常感謝您節省了我的一天。 –