SQL 在 where 子句中使用 MAX 连接两个表

SQL join between two tables with MAX in where clause

我有 table_AID 列。

-----
ID
-----
id1
id2
id3
-----

我有另一个 table_B,其中 table_A 中的每个 id 都有 latest_sub_id 以及一个日期。

---------------------------------
ID        SUB_ID     Date
---------------------------------
id1       sub_id_1   2015-01-03
id1       sub_id_2   2015-01-10
id2       sub_id_1   2015-01-02
id2       sub_id_2   2015-01-10
id2       sub_id_2   2015-01-12
id2       sub_id_3   2015-01-15
id3       sub_id_1   2015-01-09
id3       sub_id_2   2015-01-25
---------------------------------

我想在两个表之间编写一个连接查询,这样我就可以得到 MAX(DATE).

上给定 ID 值的 SUB_ID

结果应该是:

 ---------------------------------------------------------------
 ID    SUB_ID
 ---------------------------------------------------------------
 id1   sub_id_2      ---> as 10th Jan is the latest date for id1
 id2   sub_id_3      ---> as 15th Jan is the latest date for id2
 id3   sub_id_2      ---> as 25th Jan is the latest date for id3
 ---------------------------------------------------------------

你似乎真的不需要第一个 table。

使用 where 子句的一种方法是:

select b.*
from tableb b
where not exists (select 1 from tableb b2 where b2.id = b.id and b2.date > b.date);

我认为这应该有所帮助。

create table #t (ID varchar(5), sub_id varchar(20), itemDate date)

insert into #t VALUES ('id1','sub_id_1','2015-01-03')
,('id1','sub_id_2','2015-01-10')
,('id2','sub_id_1','2015-01-02')
,('id2','sub_id_2','2015-01-10')
,('id2','sub_id_2','2015-01-12')
,('id2','sub_id_3','2015-01-15')
,('id3','sub_id_1','2015-01-09')
,('id3','sub_id_2','2015-01-25')


select #t.id, sub_id,itemdate from #t inner join (select id,max(itemdate) latest from #t group by id) grouped
on #t.ID = grouped.ID and itemdate = latest

我会尝试这样的事情:

select aaa.id, bbb.id, ....
from tableA aaa Left outer join tableB bbb on aaa.id = bbb.id AND (bbb.id, bbb.subId, bbb.Date) IN (select id, subId, MAX(Date) from tableB group by id, subId)
where ....

嵌套查询是一种可行的方法。不需要 WHERE 子句。

SELECT ID, SUB_ID, Date
FROM table_B tb
INNER JOIN
    (SELECT ID, MAX(Date) as 'Date'
    FROM table_B
    GROUP BY ID) as t
ON tb.ID = t.ID AND tb.Date = t.Date

MAX 函数也不符合 WHERE 子句的语法。

您可以在这个答案中找到更多信息:SQL - Using MAX in a WHERE clause

尝试...

SELECT A.ID, B.SUB_ID, B.Date FROM table_A AS A
INNER JOIN table_B AS B ON (B.ID = A.ID)
INNER JOIN (
SELECT DISTINCT ID, MAX(Date) AS 'MaxDate' FROM table_B
GROUP BY ALL ID
HAVING COUNT(ID) = 1
) AS MX ON (MX.ID = B.ID AND MX.[MaxDate] = B.Date)