我有一个services
表,在MySQL数据库上有以下列行
`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
我正在尝试计算服务的数量以及它呈现的最后日期/时间。列created_at
是日期时间类型。
我正在运行的SQL语句是:
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
但我得到的是:
`count_service` `service_rendered` `last_rendered`
2 repair 2016-11-19 14:40:56
1 install 2016-11-19 14:40:58
如何编写我的SQL以便能够在2016-11-19 14:44:27修复?
答案 0 :(得分:4)
您可以使用created_at
列上的MAX
使用以下解决方案:
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
您想要ORDER BY created_at DESC
?
您必须使用列last_rendered
的别名,因此请将ORDER BY created DESC
替换为ORDER BY last_rendered DESC
答案 1 :(得分:0)
您必须为max(created_date)
选择created_date
而不是last_rendered
。
然后您的查询将变为
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