【发布时间】:2017-05-24 21:56:27
【问题描述】:
我有四个要加入的表来获取我需要的一些数据。表格及部分样本数据如下:
**TollTransaction table**
AccountId EntryTransDt LicPlateNo
1655024 24-05-2017 ABC123
1655024 24-05-2017 DEF123
1655024 24-05-2017 GHI123
1655024 24-05-2017 JKL123
1655024 24-05-2017 MNO123
**Plate table**
AccountId LicPlateNo EndDate
11001 ABC123 2012-06-10
1898884 ABC123 NULL
1981834 DEF123 NULL
14066 GHI123 NULL
1770746 JKL123 NULL
1005010 MNO123 NULL
**Account table**
AccountId AccountNumber CurrentBalance
11001 10110014 0
14066 10140668 0
1005010 20050108 0
1770746 27707463 3.9
1898884 28988847 0
1981834 29818345 0
**FinTransMaster table**
FinTransTypeCode BusinessDay AcctID
PYMT 03-02-2015 11001
PYMT 15-01-2015 11001
PYMT 11-12-2014 14066
PYMT 11-09-2014 14066
PYMT 01-04-2016 1005010
PYMT 02-10-2014 1005010
PYMT 15-09-2015 1770746
PYMT 30-11-2015 1898884
PYMT 21-10-2015 1898884
PYMT 23-03-2017 1981834
TollTransaction 表中的 AccountId 对于这些车牌是相同的,因为这些车牌遵循一个共同的标准。
我需要从 Plate 表中获取 AccountIds,然后在 AccountIds 上加入 Account 表以获取 AccountNumber。
我想做的事:
- 我正在尝试查找具有当前付款余额的帐户。
- 最后一次付款日期(FinTransMaster 表中的最大 BusinessDay)。
- TollTransaction 表中该 LicPlateNo 的最后一个 EntryTransDt。
我的代码如下:
SELECT A.AccountNumber
,A.CurrentBalance
,MAX(F.BusinessDay) over(Partition by F.AcctID) as Last_Pymt_date
,MAX(T.EntryTransDt) over(Partition by T.LicPlateNo) as Last_Transaction
FROM TollTransaction T
INNER JOIN Plate P ON T.LicPlateNo = P.LicPlateNo
INNER JOIN Account A ON P.AccountId = A.AccountId
LEFT JOIN FinTransMaster F ON A.AccountId = F.AcctID
WHERE T.AccountId = '1655024'
AND P.EndDate IS NULL
AND A.CurrentBalance > 0
AND F.FinTransTypeCode = 'PYMT'
ORDER BY Last_Pymt_Date DESC, A.AccountNumber
但是我的记录太多了。
我的 TollTransactions 表有多个相同 LicPlateNo 的记录。这就是为什么我在 JOIN 之后获得多条记录的原因。如果我只能将 Distinct T.LicPlateNo 加入其他表,我应该得到单个记录。
编辑: 我使用了下面提供的@SQLZim 代码,但我仍然得到一些重复。请参阅下面的部分结果:
AccountNumber CurrentBalance Last_Pymt_date Last_Transaction
1004219 40.33 24-05-2017 23-05-2017
1004219 40.33 24-05-2017 21-05-2017
1004219 40.33 24-05-2017 19-05-2017
1004219 40.33 24-05-2017 26-05-2016
1082215 60.01 24-05-2017 27-03-2017
1043516 181.25 24-05-2017 07-03-2016
1043516 181.25 24-05-2017 24-05-2017
1043516 181.25 24-05-2017 20-05-2017
1043516 181.25 24-05-2017 03-10-2015
我什至在两个地方注释掉了 T.LastTRansaction,以删除该字段。我仍然得到重复。
【问题讨论】:
标签: sql-server join