这是我一直在思考几个小时但仍然无法得到答案的事情。
假设我有这个表: table
+---------------------------------------------+
+ date | id | Country | Impressions +
+---------------------------------------------+
+ 2017-03-08 | 1 | US | 374 +
+ 2017-03-09 | 1 | US | 521 +
+ 2017-03-10 | 1 | US | 708 +
+ 2017-03-08 | 2 | US | 100 +
+ 2017-03-09 | 2 | US | 200 +
+---------------------------------------------+
我想按 id 和国家/地区对结果进行分组,但获得最后一天的印象(日期或最后一条记录的最大值)
我有这个查询
SELECT * from table group by id,country
但它给了我这个输出
+---------------------------------------------+
+ date | id | Country | Impressions +
+---------------------------------------------+
+ 2017-03-08 | 1 | US | 374 +
+ 2017-03-08 | 2 | US | 100 +
+---------------------------------------------+
如您所见,日期是第一条记录。
我想要一个给我这个输出的查询
+---------------------------------------------+
+ date | id | Country | Impressions +
+---------------------------------------------+
+ 2017-03-10 | 1 | US | 708 +
+ 2017-03-09 | 2 | US | 200 +
+---------------------------------------------+
如您所见,输出具有日期的最大值,或插入的最后一条记录
我希望你们能帮我解决这个问题,过去几个小时我一直在燃烧我的头,但没能完成。
非常感谢您提前。
获取每个 id,country 的最大日期并将此结果与原始表连接。
SELECT t.*
from table t
join (select id,country,max(date) as maxdate from table
group by id,country) t1
on t1.id=t.id and t1.country=t.country and t1.maxdate=t.date
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句