Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Select max value or last record when grouping multiple columns? [duplicate]

This is something i have been thinking for hours and still cant get the answer.

Suppose I have this table: 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      +
+---------------------------------------------+

I want to group the results by id and country, but getting the impressions on the last day (max value of date or last record)

I have this query

SELECT * from table group by id,country

but it gives me this output

+---------------------------------------------+
+     date    |  id   | Country | Impressions +
+---------------------------------------------+
+  2017-03-08 |   1   | US      |    374      +
+  2017-03-08 |   2   | US      |    100      +
+---------------------------------------------+

As you can see the date is the first record.

I want a query that gives me this output

+---------------------------------------------+
+     date    |  id   | Country | Impressions +
+---------------------------------------------+
+  2017-03-10 |   1   | US      |    708      +
+  2017-03-09 |   2   | US      |    200      +
+---------------------------------------------+

As you can see the output has the maximum value on date, or last record inserted

I hope you guys can help me on this, i have been burning my head the last hours and failed to get this done.

Thank you very much in advance.

like image 837
Lucas Avatar asked Oct 15 '25 04:10

Lucas


2 Answers

Get the max date per id,country and join this result with the original table.

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
like image 77
Vamsi Prabhala Avatar answered Oct 16 '25 19:10

Vamsi Prabhala


The problem is that you are thinking "group" rather than "filter". You don't want to aggregate any columns, so you really want to filter rows.

Here is one method for the filtering:

select t.*
from t
where t.date = (select max(t2.date)
                from t t2
                where t2.country = t.country and t2.id = t.id
               );
like image 43
Gordon Linoff Avatar answered Oct 16 '25 21:10

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!