1

This is my customer table.

Customer table

I want to group by emp_id alongwith the count. But Group By gets the 'first' record and not the 'newest' one.

I have tried various queries, 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

But cannot get the count. Please help.

Edit: this answer doesn't help to obtain count

shreyas d
  • 774
  • 1
  • 4
  • 16

2 Answers2

2

Try joining to a subquery:

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;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
-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;