Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine GROUP BY, ORDER BY and HAVING

Tags:

sql

mysql

How do I combine correctly this statement.

SELECT *, COUNT(*)
FROM user_log
GROUP BY Email
ORDER BY UpdateDate DESC
HAVING COUNT(*) > 1

Let me know

like image 482
hmmmm Avatar asked Jul 18 '11 14:07

hmmmm


People also ask

Can we use ORDER BY and having clause together?

After Grouping the data, you can filter the grouped record using HAVING Clause. HAVING Clause returns the grouped records which match the given condition. You can also sort the grouped records using ORDER BY. ORDER BY used after GROUP BY on aggregated column.

Can you have GROUP BY and ORDER BY in SQL?

Order By and Group By Clause in SQLGroup By in SQL is used to arrange similar data into groups and Order By in SQL is used to sort the data in ascending or descending order.


1 Answers

ORDER BY is always last...

However, you need to pick the fields you ACTUALLY WANT then select only those and group by them. SELECT * and GROUP BY Email will give you RANDOM VALUES for all the fields but Email. Most RDBMS will not even allow you to do this because of the issues it creates, but MySQL is the exception.

SELECT Email, COUNT(*)
FROM user_log
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY UpdateDate DESC
like image 103
JNK Avatar answered Oct 23 '22 15:10

JNK