我正在使用sqlite3查询学生数据库,其中只有 students 表。 这里重要的列是省政府和等级。
我想查看每个省的90%以上的学生所占的百分比,所以我写了以下查询:
SELECT governorate, CASE
WHEN grade > 360 AND grade <= 410 THEN '90%'
WHEN grade > 320 THEN '80%'
WHEN grade > 280 THEN '70%'
WHEN grade > 240 THEN '60%'
WHEN grade > 200 THEN '50%'
WHEN grade > 160 THEN '40%'
WHEN grade > 120 THEN '30%'
WHEN grade > 80 THEN '20%'
WHEN grade > 40 THEN '10%'
WHEN grade > 0 THEN '0%'
WHEN grade == 0 THEN '0'
END AS bucket, COUNT(*) AS number FROM students GROUP BY 1, 2;
现在,这仅告诉您每个存储桶中的学生的数量,而不是总省学生的百分比。
它为每个省创建十行,我想要的是创建一个标记为 90-100 的新列,并对该列进行ORDER BY。
答案 0 :(得分:0)
在SQLite中,您可以使用子查询:
SELECT governorate,
(CASE WHEN grade > 360 AND grade <= 410 THEN '90%'
WHEN grade > 320 THEN '80%'
WHEN grade > 280 THEN '70%'
WHEN grade > 240 THEN '60%'
WHEN grade > 200 THEN '50%'
WHEN grade > 160 THEN '40%'
WHEN grade > 120 THEN '30%'
WHEN grade > 80 THEN '20%'
WHEN grade > 40 THEN '10%'
WHEN grade > 0 THEN '0%'
WHEN grade = 0 THEN '0'
END) AS bucket,
COUNT(*) AS number,
COUNT(*) * 100.0 / c.cnt as percentage
FROM students s CROSS JOIN
(SELECT COUNT(*) as cnt FROM students) c
GROUP BY 1, 2;