revo revo - 5 months ago 7
SQL Question

Group rows count besides latest record

I can have a

group by
clause which returns latest record of each group in the way this query is running:

select `id`, `user_id`, `type`, `product_id`
from `table` where `id` in
(select max(`id`) from `table` where `product_id`=1 group by `type`)
order by `id` group by `type`


But also I want to have number of rows within each group that is counted in a normal
group by
query.

+----------+-------------------------------------------------+
| type | select count(1) where type=:type group by type; |
+----------+-------------------------------------------------+
| one | 5 |
+----------+-------------------------------------------------+
| two | 1 |
+----------+-------------------------------------------------+
| three | 109 |
+----------+-------------------------------------------------+


Is it possible to have these numbers as well?

Answer

You can do it with a JOIN :

SELECT t.id,t.user_id,t.type,t.product_id,s.cnt
FROM YourTable t
INNER JOIN (SELECT p.type,max(p.id) as max_id,count(*) as cnt
            FROM YourTable p
            WHERE p.product_id = 1
            GROUP BY p.type) s
 ON(t.id = s.max_id)
WHERE t.product_id = 1

Now the derived table s will contain for each type the max(id) and the count , and by joining to it , it will filter all the other records.

Comments