2017-07-30 115 views
0

如何將下列表格結合到此結果中?根據公共列從多個表中選擇不同的列

結果應該是idUnit的一行,該行的最新日期與Table2相匹配的那個行的ID。

我設法合併了表格,但不是基於最新的日期。

示例數據:

Table1 
id idUnit Date     extra 
1  1   2017-01-23 01:00:00 a 
2  1   2017-01-23 02:00:00 b 
3  2   2017-01-23 01:00:00 c 
4  2   2017-01-23 02:00:00 d 


Table2 
id date     extra2 
1  2017-01-23 01:00:00 w 
2  2017-01-23 02:00:00 x 
3  2017-01-23 01:00:00 y 
4  2017-01-23 02:00:00 z 


Result 
id idUnit Date     extra extra2 
2  1   2017-01-23 02:00:00 b  x 
4  2   2017-01-23 02:00:00 d  z 
+0

你應該使用顯式連接語法,這是因爲92 ANSI標準!你可以使用谷歌如何納入最大日期;這種類型的問題在很多時候都被問過許多次。 – HoneyBadger

回答

0

請使用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 
+0

這並沒有預期的結果,不幸的是。 max(日期)不是每個idUnit的最大日期,每個idUnit超過1行,id和日期的組合應該是唯一的。我認爲我可能解釋得不好,但經過篩選最大(日期)後,我預計每個idUnit(最新的)留在表1中的1行與表2連接 –

+0

因此,請您給我們一些樣本數據和預期結果?這會讓生活變得更容易。 –

+0

更新了原始問題 –

0

試試這個。在這裏這兩個表使用Inner連接進行連接。

SELECT MAX(t1.date) FROM table1 INNER JOIN table2 
ON table2.id = table1.id and table1.date= table2.date; 
0

其實你的問題主要是如何每idUnit得到最大(ID) - 之後的加入僅僅是根據ID列(簡單的內部連接) 如果你的數據庫支持它的最簡單的解決方法是使用窗口函數(分區idUnit按日期排序)

如果您的數據庫還不支持它(如MySQL 5.7),那麼你可以使用一些嵌套查詢來查找每個idUnit的最大日期的行。 (注意它通常要慢得多...)

問候,
強尼

相關問題