---
title: "找出班级里面男同学和女同学数量相同的班级"
author: "3w1h"
date: "2011-11-24T20:32:07Z"
tags: []
categories: ["数据库"]
slug: "untitled"
draft: false
lastmod: "2011-11-24T20:32:07Z"
id: 1277131
url: "https://3w1h.iteye.com/blog/1277131"
---

```sql

  select class_id
  from t_class t
 group by class_id
having sum(decode(t.sex, 'male', 1, 'female', -1, 0)) = 0;
select * from t_class;

```


```sql

select male.cid, female.cid
  from (select t1.class_id cid, count(1) total
          from t_class t1
         where t1.sex = 'male'
         group by t1.class_id) male,
       (select t2.class_id cid, count(1) total
          from t_class t2
         where t2.sex = 'female'
         group by t2.class_id) female
 where male.total = female.total
   and male.cid = female.cid;

```

两种写法  两种思路  但是第二种的写法会存在问题  考虑不全面  记下先