Mysql 条件为仅显示最大值的SQL联接表
我需要在UniqueID上加入tableA和tableB,但我只想在tableA中的最新日期加入,但有某些状态限制,不在S中。我知道我需要使用Max函数,但我无法让它工作。如何获得下表中的结果 我在想这样的事情:Mysql 条件为仅显示最大值的SQL联接表,mysql,sql,Mysql,Sql,我需要在UniqueID上加入tableA和tableB,但我只想在tableA中的最新日期加入,但有某些状态限制,不在S中。我知道我需要使用Max函数,但我无法让它工作。如何获得下表中的结果 我在想这样的事情: Select tableA.UniqueID, MAX(tableA.Date), tableA.Status, tableB.Col1 From tableA Inner join tableB on (tableB.UniqueID = t
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
;
fiddle url:请显示您编写的未产生预期输出的SQL。用您正在使用的数据库标记您的问题。添加了我在帖子中的内容