SQL select group query

后端 未结 5 1063
萌比男神i
萌比男神i 2021-02-04 13:32

Below is my Table

Table1

+--------+----------+---------+  
| amount | make     | product |  
+--------+----------+---------+  
|    100 | Nokia    | Mo         


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 13:56

    select product, make, amount, rnk
    from (
      select l.product, l.make, l.amount, count(*) as rnk
      from table1 as l
      left join table1 as r
      on (r.product = l.product and l.amount <= r.amount) 
      group by l.product, l.make
    ) a
    where rnk <= 2
    

    see the ideea and other examples here: http://www.xaprb.com/blog/2005/09/27/simulating-the-sql-row_number-function/

    and sql fiddle based on zane bien test data.

提交回复
热议问题