I have a table called order
which contains columns id
, user_id
, price
and item_id
. Item prices aren't fixed and I would like to select each item's most expensive order. I want to select user_id
, item_id
and price
in the same query. I tried the following query but it doesn't return the correct result set.
SELECT user_id, item_id, MAX(price)
FROM order
GROUP BY item_id
Some of the rows returned by this query have the wrong user_id
. However, all rows in the result set show each item's correct highest price.
SELECT MAX (column_name) FROM table_name WHERE column_name NOT IN (SELECT Max (column_name) FROM table_name); First we selected the max from that column in the table then we searched for the max value again in that column with excluding the max value which has already been found, so it results in the 2nd maximum value.
The MySQL Solution 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.
Answer. Typically, when you have more than one row that contains the minimum or maximum value in a column, the topmost row containing that value will be returned in the result.
You may want to use a derived table, as follows:
SELECT o1.item_id, o1.max_price, o2.user_id user_of_max_price
FROM (
SELECT item_id, MAX(price) max_price
FROM `order`
GROUP BY item_id
) o1
JOIN `order` o2 ON (o2.price = o1.max_price AND o2.item_id = o1.item_id)
GROUP BY o1.item_id;
Test case:
CREATE TABLE `order` (user_id int, item_id int, price decimal(5,2));
INSERT INTO `order` VALUES (1, 1, 10);
INSERT INTO `order` VALUES (1, 2, 15);
INSERT INTO `order` VALUES (1, 3, 8);
INSERT INTO `order` VALUES (2, 1, 20);
INSERT INTO `order` VALUES (2, 2, 6);
INSERT INTO `order` VALUES (2, 3, 15);
INSERT INTO `order` VALUES (3, 1, 18);
INSERT INTO `order` VALUES (3, 2, 13);
INSERT INTO `order` VALUES (3, 3, 10);
Result:
+---------+-----------+-------------------+
| item_id | max_price | user_of_max_price |
+---------+-----------+-------------------+
| 1 | 20.00 | 2 |
| 2 | 15.00 | 1 |
| 3 | 15.00 | 2 |
+---------+-----------+-------------------+
3 rows in set (0.00 sec)
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