SQL选择具有最新日期的记录

时间:2014-02-01 10:54:35

标签: sql

我想从INNER JOINED表中选择具有最新日期的记录。

Select table1.field1, table2.field1 
FROM table1
INNER JOIN table2
ON table1.field1 = table2.field1
WHERE table1.field2 = table2.field2 AND most recent date

如何在SQL中执行此操作?

3 个答案:

答案 0 :(得分:2)

Select table1.field1, t2.field1 
FROM table1
INNER JOIN 
(
   select field1, max(field2) as mdate
   from table2
   group by field1
) t2
ON table1.field1 = t2.field1 and table1.field2 = t2.mdate

答案 1 :(得分:0)

您需要按日期排序的TOP 1记录(按降序排列)

Select TOP 1 table1.field1, table2.field1 
FROM table1
INNER JOIN table2
ON table1.field1 = table2.field1
WHERE table1.field2 = table2.field2
ORDER BY date DESC

如果table2.field1不是唯一字段,我可能不是你需要的。

答案 2 :(得分:0)

假设您的table1包含一个名为date_created

的字段

试试这个

Select table1.field1, table2.field1 
FROM table1
INNER JOIN table2
ON table1.field1 = table2.field1
WHERE table1.field2 = table2.field2 AND table1.date_created between '2012-03-18' and '2013-03-18'