3

I have a services table with the following column-rows on a MySQL database

`id`    `service_rendered`  `created_at`
 1       repair              2016-11-19 14:40:56
 2       install             2016-11-19 14:40:58
 3       repair              2016-11-19 14:44:27
 4       install             2016-11-19 14:50:35

I'm trying to count the number of services and the last date/time it was rendered. Column created_at is a datetime type.

The SQL statement that I'm running is:

SELECT COUNT(`service_rendered`) as `count_service`, `service_rendered`, `created_at` as `last_rendered`
FROM services
WHERE `id` IN (1,2,3)
GROUP BY `service_rendered`
ORDER BY `created_at` DESC

But what I'm getting is:

`count_service`    `service_rendered`  `last_rendered`
 2                  repair              2016-11-19 14:40:56
 1                  install             2016-11-19 14:40:58

How do I write my SQL so that I am able to get 2016-11-19 14:44:27 on repair?

2 Answers 2

7

You can use the following solution using MAX on the created_at column:

SELECT COUNT(`service_rendered`) AS `count_service`, `service_rendered`, MAX(`created_at`) AS `last_rendered`
FROM services
WHERE `id` IN (1,2,3)
GROUP BY `service_rendered`
ORDER BY `last_rendered` DESC

demo: http://sqlfiddle.com/#!9/3906b7/2

You want to ORDER BY created_at DESC?

You have to use the alias of the column last_rendered, so replace ORDER BY created DESC with ORDER BY last_rendered DESC

0
0

You have to select the max(created_date) instead of created_date for last_rendered. Then your query will become

select 
    count(service_rendered) as count_service,
    service_rendered,
    max(created_at) as last_rendered
from
    services
group by service_rendered
order by created_at desc
1
  • You missed WHERE id IN (1,2,3) what OP have added. Nov 19, 2016 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.