I was practicing some SQL when this hit me. I wanted to see how many times a certain commodity came up and from there get the commodity which came up the most.
This shows how many times each commodity comes up:
mysql> SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count;
+----------------------+------------+
| commodity | count |
+----------------------+------------+
| PERSIAN MELON | 4 |
| BEANS | 6 |
| CASABA | 10 |
| ASPARAGUS | 11 |
| EGGPLANT | 12 |
| TOMATOES, CHERRY | 16 |
| GALIA MELON | 18 |
+-----------------------------------+
I'm trying to get the row with the highest but it's all wrong:
mysql> SELECT commodity, MAX(COUNT(commodity)) count FROM orders GROUP BY commodity ORDER BY count;
What's the right way of doing this?
If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...) Given two or more arguments, it returns the largest (maximum-valued) argument.
Discussion: To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.
In SQL Server, the MAX() function is an aggregate function that returns the maximum value in the column or expression. It is an aggregate function so it canbe used with the GROUP BY clause to find the maximum value in a group.
The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.
CAUTION: the query will not handle duplicate records having the maximum COUNT
SELECT commodity, COUNT(commodity) `count`
FROM orders
GROUP BY commodity
ORDER BY `count` DESC
LIMIT 1
But this will,
SELECT commodity, COUNT(commodity) `count`
FROM orders
GROUP BY commodity
HAVING COUNT(commodity) =
(
SELECT MAX(`COUNT`)
FROM
(
SELECT COUNT(commodity) `count`
FROM orders
GROUP BY commodity
) s
)
Try this query
SELECT commodity,COUNT(commodity) AS count
FROM orders
GROUP BY commodity
ORDER BY count desc
LIMIT 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With