I have table with id, unique_id, and order_number.
Also I have few WHERE clauses. This is my attempt which does not work:
SELECT MAX(id) AS id
, order_number
FROM table
WHERE final = 0
AND username = '$username'
AND active = 1
GROUP
BY unique_id
ORDER
BY order_number
How to get record with max value using SQL subquery. Here's the SQL query to get rows with max sale value using SQL subquery. In the above query, we first select the max value for table in subquery (in bold). Then we select those rows from original sales table where sale column value is max value.
MySQL MAX() function with GROUP BY retrieves maximum value of an expression which has undergone a grouping operation (usually based upon one column or a list of comma-separated columns).
No, you can't LIMIT subqueries arbitrarily (you can do it to a limited extent in newer MySQLs, but not for 5 results per group). This is a groupwise-maximum type query, which is not trivial to do in SQL.
You can use your query as a subquery:
SELECT *
FROM table
WHERE id IN (SELECT MAX(id) AS id
FROM table
WHERE final=0 AND username='$username' AND active=1
GROUP BY unique_id)
ORDER BY order_number
or, if id
is not unique, use JOIN
:
SELECT t1.*
FROM table AS t1
JOIN (SELECT MAX(id) AS max_id, unique_id
FROM table
WHERE final=0 AND username='$username' AND active=1
GROUP BY unique_id
) AS t2 ON t1.unique_id = t2.unique_id AND t1.id = t2.unique_id
ORDER BY order_number
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