我无法将数据限制为仅一行,最后一次付款和根据每种类型的最后日期对每个帐户进行的调整。
请注意,付款和调整可能在同一天进行,也可能只有其中一部分。因此,我需要这两种类型的最后日期和最后金额。
select
BV.AccountNumber,
BV.VisitID,
MAX(case when Type='R' then FORMAT(BCT.BatchDateTime,'MM/dd/yyyy') END) as 'PaymentDate',
(case when TransactionProcedureID like 'P%' then BCT.Amount END) as 'PaymentAmount',
max(case when Type='A' then FORMAT(BCT.BatchDateTime,'MM/dd/yyyy') END) as 'AdjustmentDate',
(case when TransactionProcedureID like 'A%' then BCT.Amount END) as 'PaymentAmount'
From BarVisits BV
JOIN BarCollectionTransactions BCT ON BCT.SourceID = BV.SourceID AND BCT.VisitID = BV.VisitID and BCT.BillingID =BV.BillingID
WHERE
AccountNumber IN ('123456789')
group by
BV.AccountNumber
,BV.VisitID
,BCT.TransactionProcedureID
,BCT.Amount
截至目前的结果
VisitID PaymentDate PaymentAmount AdjustmentDate PaymentAmount
12345 NULL NULL 05/08/2020 -4471.73
12345 NULL NULL 04/03/2020 -4286.15
12345 NULL NULL 04/23/2020 -381.70
12345 NULL NULL 04/23/2020 381.70
12345 02/24/2020 -90.00 NULL NULL
12345 04/03/2020 -392.40 NULL NULL
12345 05/08/2020 -196.12 NULL NULL
我需要查看的结果
VisitID PaymentDate PaymentAmount AdjustmentDate PaymentAmount
12345 05/08/2020 -196.12 05/08/2020 -4471.73
嗯。 。 。您似乎想过滤到最近的日期,然后使用条件聚合:
select bct.VisitID,
max(case when type = 'R' then bct.BatchDateTime end) as r_BatchDateTime,
max(case when type = 'A' then bct.amount end) as a_amount
max(case when type = 'R' then bct.BatchDateTime end) as a_BatchDateTime,
max(case when type = 'A' then bct.amount end) as a_amount
from BarVisits bv join
(select bct.*,
row_number() over (partition by bct.VisitID, bct.type order by bct.BatchDateTime desc) as seqnum
from BarCollectionTransactions bct
) bct
on bv.VisitID = bct.VisitID
where bv.AccountNumber in ('123456789') and seqnum = 1;
group by bct.VisitID;
此日期仅包含一次,因为根据定义它是相同的。