我需要在UniqueID上加入tableA和tableB,但是我只想加入tableA中具有某些状态限制的最新日期(不是在S中)。我知道我需要使用Max函数,但我不能让它工作。我如何得到下面的结果表?
我想的是:
Select
tableA.UniqueID,
MAX(tableA.Date),
tableA.Status,
tableB.Col1
From tableA
Inner join tableB on (tableB.UniqueID = tableA.UniqueID and tableA.Status = 'A')`
tableA:
| UniqueID | Date | Status |
| -------- | ------------------- |--------|
| 123 | 2015-07-05 00:00:00 | S |
| 123 | 2015-07-06 00:00:00 | S |
| 123 | 2015-07-07 00:00:00 | A |
and tableB:
| UniqueID | Col1 |
| -------- | - |
| 123 | X |
| 125 | Y |
| 126 | Z |
Result table:
| UniqueID | Date | Status | Col1|
| -------- | ------------------- |--------|---- |
| 123 | 2015-07-07 00:00:00 | A | X |
这是方法之一-
select
t_a.*, t_b.*
from
table_b t_b
join
(
select
uniqueid, date, status,
rank() over (partition by uniqueid order by date desc ) rank_
from
table_a
) t_a on t_b.uniqueid = t_a.uniqueid
where
t_a.rank_ = 1
;
小提琴url:(https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=06660177b6c116a811218863ce428985)