Alex Rivera | Logout

ROW_NUMBER() in MySQL

Asked 2009-12-12T23:58:44.780
342

Is there a nice way in MySQL to replicate the SQL Server function ROW_NUMBER()?

For example:

SELECT 
    col1, col2, 
    ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col3 DESC) AS intRow
FROM Table1

Then I could, for example, add a condition to limit intRow to 1 to get a single row with the highest col3 for each (col1, col2) pair.

Edit
Report

1 Answer

29

Check out this article; it shows how to mimic SQL's ROW_NUMBER() with a partition by in MySQL. I ran into this very same scenario in a WordPress Implementation. I needed ROW_NUMBER() and it wasn't there.

http://www.explodybits.com/2011/11/mysql-row-number/

The example in the article is using a single partition by field. To partition by additional fields you could do something like this:

SELECT @row_num := IF(@prev_value=concat_ws('',t.col1,t.col2),@row_num+1,1) AS RowNumber
    ,t.col1 
    ,t.col2
    ,t.Col3
    ,t.col4
    ,@prev_value := concat_ws('',t.col1,t.col2)
FROM table1 t,
    (SELECT @row_num := 1) x,
    (SELECT @prev_value := '') y
ORDER BY t.col1,t.col2,t.col3,t.col4 

Using CONCAT_WS() handles NULL values. I tested this against 3 fields using an INT, DATE, and VARCHAR.

answered 2011-11-18T03:15:51.590

Your Answer