从2个表中选择MAX

时间:2015-08-19 01:56:42

标签: sql db2

我有以下选择,我想在Tracct多次出现时只返回最近的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  |

1 个答案:

答案 0 :(得分:1)

您需要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