我想计算一下衬衫的尺寸,每种尺寸都必须显示不同的性别

这是我想看的输出

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 } ?>

最佳答案

您可以使用条件聚合来做到这一点:

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

09-25 23:31