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.
MariaDB 10.2 is implementing "Window Functions", including RANK(), ROW_NUMBER() and several other things:
https://mariadb.com/kb/en/mariadb/window-functions/
Based on a talk at Percona Live this month, they are reasonably well optimized.
The syntax is identical to the code in the Question.
I would also vote for Mosty Mostacho's solution with minor modification to his query code:
Which will give the same result:
for the table:
With the only difference that the query doesn't use JOIN and GROUP BY, relying on nested select instead.
The rownumber functionality can't be mimicked. You might get the results you expect, but you'll most likely get disappointed at some stage. Here's what mysql documentation says:
Regards, Georgi.
From
MySQL 8.0.0
and above you could natively use windowed functions.1.4 What Is New in MySQL 8.0:
ROW_NUMBER() over_clause :
Demo:
DBFiddle Demo
There is no funtion like
rownum
,row_num()
in MySQL but the way around is like below: