sql语句的group by与having子句

准备数据:

DROP TABLE IF EXISTS `t_player`;
CREATE TABLE `t_player` (
  `player_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(16) NOT NULL,
  `country` int(11) NOT NULL,
  `money` int(11) NOT NULL,
  PRIMARY KEY (`player_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO `t_player` VALUES ('1', '张三', '1', '1000');
INSERT INTO `t_player` VALUES ('2', '李四', '1', '1500');
INSERT INTO `t_player` VALUES ('3', '王五', '1', '2000');
INSERT INTO `t_player` VALUES ('4', '马六', '1', '2500');
INSERT INTO `t_player` VALUES ('5', 'zhangsan', '2', '1000');
INSERT INTO `t_player` VALUES ('6', 'lisi', '2', '1500');
INSERT INTO `t_player` VALUES ('7', 'wangwu', '2', '2000');
INSERT INTO `t_player` VALUES ('8', 'maliu', '2', '2500');
INSERT INTO `t_player` VALUES ('9', 'zhangsanhe', '3', '1200');
INSERT INTO `t_player` VALUES ('10', 'lisihehe', '3', '2000');
INSERT INTO `t_player` VALUES ('11', 'wangwuhe', '3', '2500');
INSERT INTO `t_player` VALUES ('12', 'maliuhe', '3', '1800');
INSERT INTO `t_player` VALUES ('13', 'wujiandao', '4', '2500');
各种查询:
1.查询money最多的5个玩家:
select * from t_player order by money DESC limit 0,5;

2.查询所有玩家money的平均值:
select AVG(money) from t_player;

3.查询每个country的所有玩家的平均值:
select country ,AVG(money) from t_player group by country;

4.查询玩家数量大于1的country的所有玩家的平均值:
select country ,AVG(money) from t_player group by country HAVING(COUNT(player_id)>1);

5.查询每个country的所有玩家的最大money、最小money:
select country,max(money),min(money) from t_player group by country;

6.查询最小money大于1100的每个country的所有玩家的最大money、最小money:
select country,max(money),min(money) from t_player group by country HAVING(MIN(money)>1100);

7.查询玩家数量最少的country:
select country,COUNT(player_id) from t_player group by country  order by count(player_id) limit 0,1;

8.查询玩家金钱总额最多的3个country:
select country,SUM(money)from t_player group by country order by SUM(money) desc limit 0,3;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值