文章参考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)tGROUP BY type
本sql使用了两重子查询,效率较低。请高人指点~