sql查询获取按销售额分组的第三高销售额

时间:2018-04-09 11:39:18

标签: mysql sql

从MySQL中的表格(按销售额分组)中获取第三高的销售额

 select Top 3 * from t1 group by sale_Amnt 

|Id|product_name|product_group    |sale_Amnt(INR)
------------------------------------------------
 1|  p1       |   Cosmetic       |4485
 2|  p2       |   Cosmetic       |8525
 3|  p3       |   Health         |12589
 4|  p4       |   Health         |8525
 5|  p5       |   Home Appliances|9858
 6|  p6       |   Home Appliances|12589

预期输出

|Id|product_name|product_group    |sale_Amnt(INR)
------------------------------------------------
 2|  p2       |   Cosmetic       |8525
 4|  p4       |   Health         |8525`

2 个答案:

答案 0 :(得分:1)

建议的副本是对问题的误解。这个问题似乎是在寻找总体上第三高的价值,但要考虑重复数据。

您可以在SQL Server中使用offset / fetch获取第三行:

select t.*
from t
where t.sale_amount = (select t2.sale_amount
                       from t t2
                       group by t2.sale_amount
                       order by t2.sale_amount desc
                       offset 2 fetch first 1 row only
                      );

在MySQL中,那将是:

select t.*
from t
where t.sale_amount = (select t2.sale_amount
                       from t t2
                       group by t2.sale_amount
                       order by t2.sale_amount desc
                       limit 1 offset 2
                      );

答案 1 :(得分:1)

SELECT * FROM `sale_amnt` ORDER BY `sale_Amnt` DESC LIMIT 2,1

相关问题