mysql先分组,然后取每个分组中的第2大的记录

文章参考http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

首先建表:

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `fruit`
-- ----------------------------
DROP TABLE IF EXISTS `fruit`;
CREATE TABLE `fruit` (
`type` varchar(10) NOT NULL,
`variety` varchar(20) NOT NULL,
`price` double(10,2) NOT NULL,
PRIMARY KEY (`type`,`variety`),
KEY `type` (`type`,`price`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of fruit
-- ----------------------------
INSERT INTO `fruit` VALUES ('apple', 'fuji', '0.24');

INSERT INTO `fruit` VALUES ('apple', 'gala', '2.79');

INSERT INTO `fruit` VALUES ('apple', 'limbertwing', '2.87');

INSERT INTO `fruit` VALUES ('apple', 'seswe', '3.84');

--------------------------------------------------------------------

INSERT INTO `fruit` VALUES ('cherry', 'bing', '2.55');

INSERT INTO `fruit` VALUES ('cherry', 'chelan', '6.33');

INSERT INTO `fruit` VALUES ('cherry', 'drtan', '7.33');

INSERT INTO `fruit` VALUES ('cherry', 'drtyd', '7.87');

---------------------------------------------------------------------

INSERT INTO `fruit` VALUES ('orange', 'valencia', '3.59');

INSERT INTO `fruit` VALUES ('orange', 'navel', '9.36');

INSERT INTO `fruit` VALUES ('orange', 'vcxss', '9.43');

INSERT INTO `fruit` VALUES ('orange', 'vbng', '11.33');

INSERT INTO `fruit` VALUES ('orange', 'cccbn', '21.36');

--------------------------------------------------------------------

INSERT INTO `fruit` VALUES ('pear', 'bartlett', '2.14');

INSERT INTO `fruit` VALUES ('pear', 'bradford', '6.05');

INSERT INTO `fruit` VALUES ('pear', 'ddssa', '8.54');

INSERT INTO `fruit` VALUES ('pear', 'rtyug', '9.07');

然后希望得到每种水果中价格第二高的数据,即:

+--------+------------+-------+
| type   | variety    | price |
+--------+------------+-------+
| apple  | limbertwig |  2.87 | 
| cherry | drtan      |  7.33 | 
| orange | vbng       | 11.33 | 
| pear   | ddssa      |  8.54 | 
+--------+------------+-------+

参考如下sql语句:

SELECT t.type,MIN(t.price) price FROM(SELECT
    a.type,a.price
    FROM fruit a
    WHERE
      2 >= (
          SELECT
          COUNT(*)
          FROM
          fruit b
          WHERE
          a.type= b.type
          AND a.price <= b.price
         )
    ORDER BY
    a.type,
    a.price)t

GROUP BY type

本sql使用了两重子查询,效率较低。请高人指点~
posted @   达摩克利斯之剑  阅读(2539)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示