Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT row with MAX id from each GROUP BY (unique_id) and ORDER BY number

Tags:

mysql

I have table with id, unique_id, and order_number.

  1. I want to GROUP rows by unique_id
  2. I want to take row with MAX id from each group
  3. And last thing I want to sort that rows by 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
like image 343
user3100193 Avatar asked Mar 08 '16 12:03

user3100193


People also ask

How do I get the highest row value in SQL?

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.

How do you find the maximum value of GROUP BY?

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).

Can we use limit with GROUP BY in SQL?

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.


1 Answers

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
like image 89
Giorgos Betsos Avatar answered Sep 20 '22 05:09

Giorgos Betsos