SQL select group query

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

Below is my Table

Table1

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


        
相关标签:
5条回答
  • 2021-02-04 13:51
    select top 2 amount, make, product from table1 
    where product='Mobiles'
    order by amount desc
    union
    select top 2 amount, make, product from table1 
    where product='Gift'
    order by amount desc
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-04 14:03
    SELECT a.*
    FROM Table1 a
    INNER JOIN Table1 b ON a.product = b.product AND a.amount <= b.amount
    GROUP BY a.amount, a.product
    HAVING COUNT(*) <= 2
    ORDER BY a.amount desc
    

    Please refer to http://sqlfiddle.com/#!2/9ba82/1

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2021-02-04 14:14

    You can use this solution to retrieve the "group-wise maximum" based on the amount:

    SELECT a.*
    FROM Table1 a
    INNER JOIN Table1 b ON a.product = b.product AND a.amount <= b.amount
    GROUP BY a.amount, a.product
    HAVING COUNT(*) <= 2
    

    Simply change the 2 to however many of the top rows you want to retrieve per product.

    If you wanted to retrieve the lowest two rows per product, you can simply change the <= sign in the INNER JOIN to a >=.

    You can fiddle around with this solution here: SQL-Fiddle Demo

    0 讨论(0)
提交回复
热议问题