Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Find highest occurrence of a column value in a table?

Tags:

sql

sql-server

I'm trying to find the most ordered menu item in a table by counting the occurrences of their item id. I've tried a few different things but I'm pretty lost. This produced the error:

"An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference."

However I think it puts into perspective what I'm trying to achieve:

SELECT count(itemCode) 
FROM OrderProcessing 
WHERE count(itemCode)=max(count(itemCode))
like image 626
camohreally Avatar asked May 24 '15 16:05

camohreally


People also ask

How do you find the most repeated value in a column SQL?

How do you find the most repeated value in a column SQL? select cnt1. column_name from (select COUNT(*) as total, column_name from table_name group by column_name) cnt1, (select MAX(total) as maxtotal from (select COUNT(*) as total, column_name from table_name group by column_name)) cnt2 where cnt1.

How do you find the maximum occurrence in SQL?

One option could be to group by the field, order by the count of appearence descanding and taking the first result; other option could be to use the row_number or rank function in SQL Server 2005 or higher.

Can we use Max on a column?

Expression made up of a single constant, variable, scalar function, or column name or any combination of arithmetic, bitwise, and string operators. MAX can be used with numeric, character, and datetime columns, but not with bit columns. Aggregate functions and subqueries are not permitted.


2 Answers

I. modified version of original query (UPDATE after @DanGuzman comment about ties)

select all items with the same count as most wanted item:

SELECT itemCode , count(*) as MaxCount
FROM OrderProcessing
GROUP BY itemCode
HAVING count(*) = 
-- count of most wanted item
(select top 1 count(*) 
 from OrderProcessing 
 group by itemCode 
 order by count(*) desc)

II. the query to select one of most ordered items

SELECT top 1 itemCode --, count(*) as MaxCount  --optional
FROM OrderProcessing
GROUP BY itemCode
ORDER BY count(*) DESC
like image 61
ASh Avatar answered Sep 30 '22 22:09

ASh


If you want one row, I would suggest order by:

SELECT TOP 1 itemCode, count(itemCode)
FROM OrderProcessing
GROUP BY itemCode
ORDER BY count(itemCode);

If you want all items with the maximum count, use WITH TIES:

SELECT TOP 1 WITH TIES itemCode, count(itemCode)
FROM OrderProcessing
GROUP BY itemCode
ORDER BY count(itemCode);

If you want to be fancy, use window functions. Here is an example:

SELECT itemCode, cnt
FROM (SELECT itemCode, count(itemCode) as cnt,
             MAX(count(itemCode)) OVER () as maxcnt
      FROM OrderProcessing
      GROUP BY itemCode
     ) op
WHERE cnt = maxcnt;
like image 25
Gordon Linoff Avatar answered Sep 30 '22 23:09

Gordon Linoff