表User有字段:name,sex,classId,比如有如下記錄:
a, 男, 1
b, 男, 1
c, 女, 1
d, 女, 1
e, 男, 2
f, 男, 2
要求查出如下這樣的記錄(每個(gè)班男、女各有幾人):
classId 男 女
1 2 2
2 1 1
請(qǐng)問(wèn)要怎樣寫(xiě)?
如果只是查出每個(gè)班的男生人數(shù)就會(huì):
SELECT class, COUNT(*) AS '男' FROM t_uu WHERE sex='男' GROUP BY class;
光陰似箭催人老,日月如移越少年。
Command:
SELECT class_id, SUM(sex = '男') AS male, SUM(sex = '女') AS female FROM student
GROUP BY class_id
Result:
Original data:
select * from student;
The data is wrong, isn’t it? If the classid is 2, there should be only 2 boys o(╯□╰)o
My answer is based on the original poster’s knowledge, and of course mine too:
First find out the situation of boys, such as t1:
|class_id|male|
|:---:|:---:|
|1|2|
|2|1|
Then find out the girl’s situation, such as t2:
class_id | female |
---|---|
1 | 2 |
2 | 1 |
Finally, chain the two watches together: select t1.class_id,male,female from t1,t2 where t1.class_id = t2.class_id
I haven’t tried it, but it probably means the right thing