Mysql Group By获取有关Count

时间:2018-11-16 07:05:10

标签: mysql sql

这是我的客户表。

Customer table

我想按emp_id和计数分组。但是Group By获得的是“第一”记录,而不是“最新的”记录。

我尝试了各种查询,like this

SELECT id, emp_id, COUNT( * ) AS count, created_at
FROM  customer c
WHERE  created_at = (
SELECT MAX(  created_at ) 
FROM  customer c2
WHERE c2.emp_id = c.emp_id
)
GROUP BY  emp_id 
ORDER BY  created_at DESC 
LIMIT 0 , 30

enter image description here

但是无法计数。请帮忙。

编辑:this answer不利于获得计数

2 个答案:

答案 0 :(得分:2)

尝试加入子查询:

SELECT c1.id, c1.emp_id, c1.created_at, c2.cnt
FROM customer c1
INNER JOIN
(
    SELECT emp_id, MAX(created_at) AS max_created_at, COUNT(*) AS cnt
    FROM customer
    GROUP BY emp_id
) c2
    ON c1.emp_id = c2.emp_id AND c1.created_at = c2.max_created_at;

答案 1 :(得分:-1)

please try this 
SELECT cust1.id, cust1.emp_id, cust1.created_at, cust2.cnt
FROM customer cust1
INNER JOIN
(
    SELECT emp_id, MAX(created_at) AS max_created_at, COUNT(*) AS count
    FROM customer
    GROUP BY emp_id
) cust2
    ON cust1.emp_id = cust2.emp_id AND cust1.created_at = cust2.max_created_at;