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;

你可能感兴趣的:(sql语句的group by与having子句)