SQL计数大小和性别

时间:2015-06-20 11:07:25

标签: php mysql sql database

我想计算衬衫尺寸,每个尺码必须显示不同的性别

这是我想看的输出

Size Qty Male Female 

S    20   15     5
M    30   20    10

这是我的一些SQL语言和PHP代码,但这只查询每个大小的数量。

$stmt = $con->prepare("SELECT ssize,COUNT(*) FROM students GROUP BY ssize");

$stmt->execute();

<?php while($rs = $stmt->fetch()) { ?>

    <?=$rs['ssize']." ".number_format($rs["COUNT(*)"])?> 

<?php } ?>

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合执行此操作:

SELECT s.ssize, COUNT(*),
       SUM(s.gender = 'M') as Male, SUM(s.gender = 'F') as Female
FROM students s
GROUP BY s.ssize;