内部联接没有左表的重复值?

时间:2016-08-15 11:12:12

标签: sql sql-server sql-server-2008

我正在使用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

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要一个发票服务,以及#34;真的"比赛。

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