鉴于下表:
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
如何为每个date1仅选择一行,其中date2是最近的日期?
所以最终的输出是:
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
换句话说,我只为每个date1和代码保留date2的最高值。
答案 0 :(得分: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)
答案 1 :(得分:1)
听起来你只想要一个简单的GROUP BY
查询:
SELECT code, date1, MAX(date2)
FROM yourTable
GROUP BY code, date1
答案 2 :(得分:0)
select code, date1, max(date2) as date2 from table group by code, date1