0
我有4个表,我需要加入从中提取数据:如何在SQL Server 2014的JOIN中获取MAX值?
| Account Table: A | Plate Table: P | TollTransaction : T | FinTrans Table: F |
=================================================================================
| AccountId | AccountId | AccountId | AcctId |
| AccountNumber | LicPlateNo | LicPlateNo | FinTransTypeCode |
| CurrentBalance | EndDate | EntryTransDt | BusinessDay |
| ActualTagDeposit | | | |
=================================================================================
的关系:
A.AccountId = P.AccountId = F.AcctId != T.AccountId <--(NOT EQUAL)
P.LicPlateNo = T.LicPlateNo
我想表明:
A.AccountNumber
A.CurrentBalance
Max(BusinessDay) -->(Last Payment Date)
Max(EntryTransDt) -->(Last Transaction Date)
ActualTagDeposit
WHERE P.EndDate IS NULL
AND A.CurrentBalance > 0
AND F.FinTransTypeCode = 'pymt'
AND Max(EntryTransDt) <= '2017-07-28'
AND A.ActualTagDeposit >= 10
我的代码尝试到目前为止:
SELECT A.AccountNumber
,A.CurrentBalance
,MAX(F.Last_Pymt_date) AS Last_Pymnt_Date
,MAX(T.Last_Transaction) AS LastTransaction
,A.ActualTagDeposit
FROM
(SELECT AccountId
,LicPlateNo
,MAX(EntryTransDt) AS Last_Transaction
FROM TollTransaction
GROUP BY AccountId, LicPlateNo
) T
INNER JOIN Plate P ON T.LicPlateNo = P.LicPlateNo
INNER JOIN Account A ON P.AccountId = A.AccountId
LEFT JOIN
(SELECT AcctId
,FinTransTypeCode
,MAX(BusinessDay) AS Last_Pymt_Date
FROM FinTransMaster
GROUP BY AcctID, FinTransTypeCode
) F ON A.AccountId = F.AcctId
WHERE P.EndDate is null
AND A.CurrentBalance > 0
AND F.FinTransTypeCode = 'pymt'
AND Last_Transaction <= '2017-07-28'
AND A.ActualTagDeposit >= 10
GROUP BY AccountNumber, CurrentBalance, Last_Pymt_date, Last_Transaction, A.ActualTagDeposit
ORDER BY AccountNumber
但我得到与此代码重复。显然,我的代码中的MAX
部分无法正常工作?
结果我得到的样品:
AccountNumber CurrentBalance Last_Pymnt_Date LastTransaction ActualTagDeposit
21233815 12.34 2016-12-12 2016-08-15 10.00
21233815 12.34 2016-12-12 2017-03-11 10.00
21234567 123.12 2017-06-20 2016-12-25 10.00
21234568 1.23 2017-06-05 2012-07-12 10.00
21234568 1.23 2017-06-05 2012-07-21 10.00
删除'LAST_Pymnt_Date'和' “GROUP BY”中的Last_Transaction' –
好吧,所以您已经确定最大(最后一个事务)不起作用。那会让你看到那张桌子。你不是由来自该表的其他东西组成的。 我的猜想:可能你有多个牌照的帐户? –
是的。我的帐号有多个牌照。但我只是想要最后的过境,不管哪个车牌越过。 – user1777929