2016-07-15 123 views
0

假設表格如下:MySQL的選擇不同日期查詢

code date1    date2 
393517 07/07/2016 00:00 08/07/2016 00:00 
393517 07/07/2016 00:00 11/07/2016 00:00 
393517 07/07/2016 00:00 12/07/2016 00:00 
393517 07/07/2016 00:00 13/07/2016 00:00 
393517 08/07/2016 00:00 11/07/2016 00:00 
393517 08/07/2016 00:00 12/07/2016 00:00 
393517 08/07/2016 00:00 13/07/2016 00:00 
393517 11/07/2016 00:00 12/07/2016 00:00 
393517 11/07/2016 00:00 13/07/2016 00:00 
393516 07/07/2016 00:00 08/07/2016 00:00 
393516 07/07/2016 00:00 11/07/2016 00:00 
393516 07/07/2016 00:00 12/07/2016 00:00 
393516 07/07/2016 00:00 13/07/2016 00:00 
393516 08/07/2016 00:00 11/07/2016 00:00 
393516 08/07/2016 00:00 12/07/2016 00:00 
393516 08/07/2016 00:00 13/07/2016 00:00 
393516 11/07/2016 00:00 12/07/2016 00:00 
393516 11/07/2016 00:00 13/07/2016 00:00 

如何選擇其中date2的是最近的日期各DATE1只有一排?

所以,最後的結果將是:

code date1    date2 
393517 07/07/2016 00:00 13/07/2016 00:00 
393517 08/07/2016 00:00 13/07/2016 00:00 
393517 11/07/2016 00:00 13/07/2016 00:00 
393516 07/07/2016 00:00 13/07/2016 00:00 
393516 08/07/2016 00:00 13/07/2016 00:00 
393516 11/07/2016 00:00 13/07/2016 00:00 

換句話說,我將只保留date2的最高值爲每個日期1和代碼。

+0

的'集團BY'最簡單的使用情況。 – 1000111

回答

2

嘗試

SELECT t1.* 
FROM Table1 t1 
WHERE t1.date2 = (SELECT MAX(t2.date2) 
      FROM Table1 t2 
      WHERE t2.date1 = t1.date1 AND t2.code=t1.code) 
0
select code, date1, max(date2) as date2 from table group by code, date1 
1

這聽起來像是你只是想要一個簡單的GROUP BY查詢:

SELECT code, date1, MAX(date2) 
FROM yourTable 
GROUP BY code, date1