SELECT paid,schoolsup,famsup,nursery from student_mat GROUP BY paid,schoolsup,famsup,nursery 计算这个语句中 4个/3个/2个/1个yes的个数 用一个sql语句 不分开查询
时间: 2024-02-15 08:05:43 浏览: 107
可以使用以下 SQL 语句实现:
```
SELECT
SUM(CASE WHEN paid='yes' THEN 1 ELSE 0 END) AS paid_yes_count,
SUM(CASE WHEN schoolsup='yes' THEN 1 ELSE 0 END) AS schoolsup_yes_count,
SUM(CASE WHEN famsup='yes' THEN 1 ELSE 0 END) AS famsup_yes_count,
SUM(CASE WHEN nursery='yes' THEN 1 ELSE 0 END) AS nursery_yes_count,
SUM(CASE WHEN paid='yes' AND schoolsup='yes' AND famsup='yes' AND nursery='yes' THEN 1 ELSE 0 END) AS all_yes_count,
SUM(CASE WHEN (paid='yes' AND schoolsup='yes' AND famsup='yes') OR (paid='yes' AND schoolsup='yes' AND nursery='yes') OR (paid='yes' AND famsup='yes' AND nursery='yes') OR (schoolsup='yes' AND famsup='yes' AND nursery='yes') THEN 1 ELSE 0 END) AS three_yes_count,
SUM(CASE WHEN (paid='yes' AND schoolsup='yes') OR (paid='yes' AND famsup='yes') OR (paid='yes' AND nursery='yes') OR (schoolsup='yes' AND famsup='yes') OR (schoolsup='yes' AND nursery='yes') OR (famsup='yes' AND nursery='yes') THEN 1 ELSE 0 END) AS two_yes_count,
SUM(CASE WHEN paid='yes' OR schoolsup='yes' OR famsup='yes' OR nursery='yes' THEN 1 ELSE 0 END) AS one_yes_count
FROM student_mat;
```
其中,`student_mat` 为实际表名,以上语句中的 `yes` 可能需要根据实际情况替换为其他值。语句中的结果将会返回四个字段,分别对应 paid、schoolsup、famsup 和 nursery 字段中值为 yes 的个数。同时,还将会返回四个不同的计数,分别对应四种不同情况下的 yes 的个数,包括同时参加四个、三个、两个和一个的个数。
阅读全文