How to get RowNumber() with Partition in MYSQL

核能气质少年 提交于 2019-11-28 01:45:10

I barely understood what you mean. There's no RowNumber() function in mysql, and partitioning has nothing to do with your request.

It's:

SELECT 
  t.*, 
  @cur:= IF(id=@id, @cur+1, 1) AS RowNumber, 
  @id := id 
FROM 
  t CROSS JOIN 
    (SELECT @id:=(SELECT MIN(id) FROM t), @cur:=0) AS init 
ORDER BY 
  t.id

@Alma Du, @Chintu is talking about SQL Server where you can apply row_number + partition over specific field(s).

Practical Example: Imagine that you have a table - named 'customerPurchasesHist' - that stores customer's purchases history:

| customerNr | purchaseItem | purchaseDatetime |
| 123        | microwave    | 2014-06-05       |
| 123        | television   | 2014-09-10       |
| 123        | fridge       | 2015-01-10       |
| 1234       | sofa         | 2015-01-10       | 
(....)

In SQL Server, if you need to get the last two purchases from each client on that table, all you have to do is:

SELECT * FROM (
   SELECT h.*, ROW_NUMBER() OVER (PARTITION BY customerNr ORDER BY purchaseDatetime DESC) AS sequence 
   FROM customerPurchasesHist h
)T
WHERE 1=1
AND seq <= 2
;

The result will be:

| customerNr | purchaseItem | purchaseDatetime | seq |
| 123        | fridge       | 2015-01-10       |  1  |
| 123        | television   | 2014-09-10       |  2  |
| 1234       | sofa         | 2015-01-10       |  1  |
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!