SQL Server完全连接查询 - 只获得一次结果

时间:2018-06-03 15:19:00

标签: sql sql-server

我想显示如下结果:

Date      InvoiceNo  SalesAmount   Date     PaymentType  CheckNo  ReceivedAmount
================================================================================
03-28-2018  C2803       1253.25    Null         Null      Null      Null
03-30-2018  C3001       563.80     Null         Null      Null      Null
04-02-2018  C0205       2311.66    04-02-2018   Check     1253      1816.25
Null        Null        Null       04-05-2018   Check     3565      2311.66
04-06-2018  C0601       560.00     04-06-2018   Check     5231      230.00
04-06-2018  C0602       280.00     Null         Null      Null      Null
04-08-2018  C0805       153.66     04-08-2018   Check     6523      330.00
Null        Null        Null       04-08-2018   Check     6524      280.00

发票可能每天发出多次,收集可能每天发生几次。

我的查询的问题是,当每天生成两张发票并且只收集一个集合时,收集结果会重复两次。

如何只显示一次结果?

enter image description here

查询:

select
    S.Date as SDate, S.InvoiceNo, S.SalesAmount, P.Date as PDate, 
    P.PaymentType, P.CheckNo, P.ReceivedAmount
from
    SalesHistory S
full outer join 
    PaidHistory P ON P.Date = S.Date
where
    S.CustCode = '1701' or P.CustCode = '1701'
order by
    isnull(S.Date, P.Date)

1 个答案:

答案 0 :(得分:1)

您可以添加ROW_NUMBER并加入其中:

select
  S.Date as SDate, S.InvoiceNo, S.SalesAmount, P.Date as PDate, P.PaymentType, P.CheckNo, P.ReceivedAmount
from
 ( select *,
      row_number() over (partition by CustCode, Date order by InvoiceNo) as rn
   from SalesHistory
   where CustCode='1701'
 ) S
Full outer Join 
 ( select *,
      row_number() over (partition by CustCode, Date order by CheckNo) as rn
   from PaidHistory
   where CustCode='1701'
 ) P
ON P.CustCode = S.CustCode
and P.Date=S.Date
and s.rn = p.rn
order by
  ISNULL(S.Date,P.Date)

我将CustCode添加到row_numbers和join中,以防万一您想要使用多个客户运行它。