2016-08-15 2 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 

나는 왼쪽 테이블에서 비 중복 값을 얻을 필요가 :

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

사용하지 않는 DB 엔진에 태그를 지정하지 마십시오. –

+0

별개의 선택으로 왼쪽 결합을 사용하십시오. http://www.w3schools.com/sql/sql_distinct.asp, http://www.w3schools.com/sql/sql_join_left.asp – tenten

답변

1

: 를 송장 1 개 이상의 서비스를 제공 할 때 나는 송장 가격과 InvoicePaidAmount이 예처럼 반복되지 않도록하려면 제가 올바르게 이해한다면, 당신은 하나의 인보이스 서비스가 "정말로"매치되기를 원할 것입니다.

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

대단히 감사합니다. –

관련 문제