hovado
hovado

Reputation: 4958

MySQL: select last (max) value from column and count of all rows

How can I select last (=max) value from column and count of all rows in single query?

ID      ITEM_ID       VALUE
1       1             100
2       1             101
3       2             201
4       3             333
5       2             222
6       1             111

I want to select last / max value for particular ITEM_ID and count of all rows with this ID. For ITEM_ID = 1 thus:

VALUE      COUNT
111        3

My query is like this:

SELECT (SELECT COUNT(*) FROM table) AS count, (SELECT value FROM table ORDER BY id DESC LIMIT 1) AS value FROM table WHERE item_id = 1 LIMIT 1

It works but looks ... weird. Is there any better (simpler / faster) solution? Thanks

Upvotes: 1

Views: 1097

Answers (1)

Rahul
Rahul

Reputation: 77906

You need to do a GROUP BY on column ITEM_ID while getting the MAX() and COUNT() like

select max(value) as `VALUE`,
count(*) as `COUNT`
from your_table
group by ITEM_ID;

Upvotes: 2

Related Questions