mysql 分组选取第n_mysql实现先分组后排序取N个

本文展示了如何使用SQL查询从`test`表中获取每个公司价格排名前三的产品。通过两种不同的子查询方法,实现了按公司分组并按价格降序排列的数据检索。这些技巧对于数据分析师和数据库管理员在处理大数据时非常有用。
摘要由CSDN通过智能技术生成

SET FOREIGN_KEY_CHECKS=0;

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

-- Table structure for `test`

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

DROP TABLE IF EXISTS `test`;

CREATE TABLE `test` (

`company` varchar(255) DEFAULT NULL,

`product` varchar(255) DEFAULT NULL,

`price` int(11) DEFAULT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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

-- Records of test

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

INSERT INTO `test` VALUES ('a', 'a1', '11');

INSERT INTO `test` VALUES ('a', 'a2', '22');

INSERT INTO `test` VALUES ('a', 'a3', '33');

INSERT INTO `test` VALUES ('b', 'b1', '99');

INSERT INTO `test` VALUES ('b', 'b2', '88');

INSERT INTO `test` VALUES ('b', 'b3', '77');

INSERT INTO `test` VALUES ('b', 'b4', '66');

INSERT INTO `test` VALUES ('c', 'c1', '44');

INSERT INTO `test` VALUES ('c', 'c2', '55');

INSERT INTO `test` VALUES ('c', 'c3', '66');

INSERT INTO `test` VALUES ('c', 'c4', '77');

--方式一

select * from test t1 where 3 > (select count(*) + 1  from test where company = t1.company and price > t1.price ) order by company , price desc

-- 方式二

select * from ( select *  ,(select count(*) + 1 from test where company = t1.company and price > t1.price) group_id from test t1) t where group_id < 3 order by t.company , t.price desc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值