Select MAX 来自 2 个表

Select MAX from 2 tables

我有以下 select,我想 return 当 Tract 不止一次出现时,我只想 return 最近的 TranDate。

SELECT tracct, trancd, trnsta, date(digits(trdat7)) as TranDate, type 
FROM DATALIBRARY.LNHIST LNHIST 
JOIN DATALIBRARY.LNMAST LNMAST 
  on LNHIST.TRACCT = LNMAST.ACCTNO 
WHERE YEAR(date(digits(trdat7))) >= YEAR(current_date) - 2 and trnsta = '1' and trancd = 891 and type not like 'I%'

当前结果:

|Tracct | Trancd | Trnsta | TranDate   | Type|
----------------------------------------------
 425660 | 891    | 1      | 2013-05-10 | C5  |
 102649 | 891    | 1      | 2013-05-10 | C5  |
 102741 | 891    | 1      | 2015-08-08 | RO  |
 102741 | 891    | 1      | 2015-09-10 | RO  |
 102741 | 891    | 1      | 2014-05-10 | RO  |
 115298 | 891    | 1      | 2013-03-31 | CV  |
 102313 | 891    | 1      | 2015-04-10 | CL  |
 102313 | 891    | 1      | 2015-05-10 | CL  |

你需要一个nested query

调用您的查询 SUBQUERY

我想你想要

SELECT Tracct, Trancd, Trnsta, Type, MAX(TranDate)
FROM SUBQUERY
GROUP BY Tracct, Trancd, Trnsta, Type

或者您可以将查询重写为类似这样的内容

SELECT tracct, trancd, trnsta, type, MAX(date(digits(trdat7))) as TranDate 
FROM DATALIBRARY.LNHIST LNHIST 
JOIN DATALIBRARY.LNMAST LNMAST 
  on LNHIST.TRACCT = LNMAST.ACCTNO 
WHERE YEAR(date(digits(trdat7))) >= YEAR(current_date) - 2 and trnsta = '1' and trancd = 891 and type not like 'I%'
GROUP BY tracct, trancd, trnsta, type