How to get RowNumber() with Partition in MYSQL

前端 未结 2 1425
借酒劲吻你
借酒劲吻你 2020-12-02 01:40

RowNumber() with Partition in MYSQL

i want the below output based on id-Foreign key

 id | Name | rownumber
 1     a      1
 1     b      2
 1     ads         


        
2条回答
  •  独厮守ぢ
    2020-12-02 02:03

    @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  |
    

提交回复
热议问题