請使用JOIN現代語法,而不是逗號分隔的表用在哪裏。
所以,你的SQL變得
select t1.id, t1.idUnit, MAX(t1.date), t1.?, t2.? from table1 t1 INNER JOIN table2 t2
ON t1.id = t2.id and t1.date = t2.date
GROUP BY t1.id, t1.idUnit, t1.?, t2.?
請注意,您必須在GROUP BY所有你在SELECT希望等領域包括(在那裏我有T1?和t2。?作爲佔位符)
編輯
看過示例數據,請嘗試以下操作。如果您使用SQL Server,則可以複製整個事件並粘貼到查詢窗口中。可以在任何數據庫中完成與以下所用類似的子查詢方法。
declare @table1 table
(
id int,
idUnit int,
tDate datetime,
extraCol varchar(10)
)
declare @table2 table
(
id int,
tDate datetime,
extraCol varchar(10)
)
INSERT INTO @table1 VALUES(1, 1, '2017-01-23 01:00:00', 'a')
INSERT INTO @table1 VALUES(2, 1, '2017-01-23 02:00:00', 'b')
INSERT INTO @table1 VALUES(3, 2, '2017-01-23 01:00:00', 'c')
INSERT INTO @table1 VALUES(4, 2, '2017-01-23 02:00:00', 'd')
INSERT INTO @table2 VALUES(1, '2017-01-23 01:00:00', 'w')
INSERT INTO @table2 VALUES(2, '2017-01-23 02:00:00', 'x')
INSERT INTO @table2 VALUES(3, '2017-01-23 01:00:00', 'y')
INSERT INTO @table2 VALUES(4, '2017-01-23 02:00:00', 'z')
SELECT t1.id, t1.idUnit, t1.tDate, t1.extraCol, t2.extraCol FROM @table1 t1
INNER JOIN @table2 t2 ON t1.id = t2.id and t1.tDate = t2.tDate
INNER JOIN
(SELECT idUnit, MAX(tDate) as maxDate FROM @table1
GROUP By idUnit) m
ON t1.idUnit = m.idUnit and t1.tDate = m.maxDate
ORDER BY id
你應該使用顯式連接語法,這是因爲92 ANSI標準!你可以使用谷歌如何納入最大日期;這種類型的問題在很多時候都被問過許多次。 – HoneyBadger