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使用了两重子查询,效率较低。请高人指点~

转载于:https://www.cnblogs.com/damour-damocles/p/4975243.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值