SQL COUNT* GROUP BY bigger than,

SqlCountGroup By

Sql Problem Overview


I want to select the distinct keys with the occurence number, this query seems functionate:

SELECT ItemMetaData.KEY, ItemMetaData.VALUE, count(*) 
FROM ItemMetaData 
GROUP BY ItemMetaData.KEY 
ORDER BY count(*) desc;

But I also want to filter these result, meaning I want only where count(*) is greater than 2500 so only bigger than 2500 occurence will shown, but:

SELECT * 
FROM 
(
    SELECT ItemMetaData.KEY, ItemMetaData.VALUE, count(*) 
    FROM ItemMetaData 
    GROUP BY ItemMetaData.KEY 
    ORDER BY count(*) desc
) as result WHERE count(*)>2500;

Unfortunately this query results in a syntax error. Can you help me achieve my requirement?

Sql Solutions


Solution 1 - Sql

HAVING clause for aggregates

SELECT ItemMetaData.KEY, ItemMetaData.VALUE, count(*) 
FROM ItemMetaData 
Group By ItemMetaData.KEY, ItemMetaData.VALUE
HAVING count(*) > 2500
ORDER BY count(*) desc;

Solution 2 - Sql

You should use having with group functions instead of where. E.g.:

select ..., count(*) from ... group by ... having count(*) > 2500;

Solution 3 - Sql

You do not need to use a subquery - simply use a having clause instead of where clause to filter by an aggregated column.

SELECT
ItemMetaData.KEY, ItemMetaData.VALUE, count(*)
FROM ItemMetaData
GROUP BY ItemMetaData.KEY
HAVING count(*) > 2500
ORDER BY count(*) desc

Solution 4 - Sql

Here is the explanation: WHERE clause introduces a condition on individual rows; HAVING clause introduces a condition on aggregations.

Use WHERE before GROUP BY and HAVING after GROUP BY. It isn't mandatory, but helpuful in most cases.

SELECT 
       ItemMetaData.KEY, ItemMetaData.VALUE, СOUNT(*) 
FROM  ItemMetaData 
GROUP BY
       ItemMetaData.KEY, ItemMetaData.VALUE
HAVING СOUNT(*) > 2500
ORDER BY СOUNT(*) DESC;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionczupeView Question on Stackoverflow
Solution 1 - SqlBillView Answer on Stackoverflow
Solution 2 - SqlAndrew LogvinovView Answer on Stackoverflow
Solution 3 - SqlSergey KalinichenkoView Answer on Stackoverflow
Solution 4 - SqlAleksei LitvinauView Answer on Stackoverflow