SQL select group query

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

Below is my Table

Table1

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


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 14:09

    You can do it in two ways: 1) Add Row Index column that will reflect the order and then select all rows with Row <= 2

    SELECT amount, make,product
    FROM 
    (SELECT  ROW_NUMBER() OVER (PARTITION BY [product] ORDER BY [amount] DESC) AS [RowID],*
    FROM [dbo].[Table1]) RESULT
    WHERE RowID <= 2
    

    2) You can also join the table to itself

    SELECT a1.* FROM Table1 AS a1
      LEFT JOIN Table1 AS a2 
        ON a1.product = a2.product AND a1.amount<= a2.amount
    GROUP BY a1.product
    HAVING COUNT(*) <= 2;
    

提交回复
热议问题