5.统计每个班级男女生人数最多的3条记录(去null值)
时间: 2024-10-27 17:03:28 浏览: 29
如果你想统计每个班级男女各自人数最多的情况,并保留三条记录(去除了null值),这通常涉及到两个步骤:首先,分别统计男生和女生在每个班级的数量;然后,取每个班级人数最多的前三名。这在SQL中可以表示为:
```sql
WITH male_counts AS (
SELECT class_id, gender, COUNT(*) as count
FROM users_info
WHERE gender = '男' AND age IS NOT NULL
GROUP BY class_id, gender
),
female_counts AS (
SELECT class_id, gender, COUNT(*) as count
FROM users_info
WHERE gender = '女' AND age IS NOT NULL
GROUP BY class_id, gender
)
SELECT m.class_id, '男' as gender, m.count
FROM male_counts m
JOIN (SELECT class_id, MAX(count) as max_male_count
FROM male_counts
GROUP BY class_id) mm ON m.class_id = mm.class_id AND m.count = mm.max_male_count
LIMIT 3
UNION ALL
SELECT f.class_id, '女' as gender, f.count
FROM female_counts f
JOIN (SELECT class_id, MAX(count) as max_female_count
FROM female_counts
GROUP BY class_id) mf ON f.class_id = mf.class_id AND f.count = mf.max_female_count
LIMIT 3;
```
这个查询创建了两个窗口函数子查询(male_counts 和 female_counts),用于计算每个班级的男生和女生人数,然后通过`JOIN`和`MAX()`函数找到每个班级人数最多的记录,并使用`UNION ALL`合并结果,最后限制返回的结果集最多为每种性别各三条记录。
阅读全文