我有一张如下表,
如何编写查询以获取此信息
您没有指定您使用的数据库产品,但您应该能够在任何数据库中使用带有 CASE 表达式的聚合函数来获得结果:
select subject,
sum(case when marks > 10 and marks <= 40 then 1 else 0 end) Range10_40,
sum(case when marks > 40 and marks <= 60 then 1 else 0 end) Range40_60
from yt
group by subject;
试试这个查询
对于 MySQL
SELECT
subject,
sum(if(marks between 10 and 40, 1, 0)) as '(10-40)',
sum(if(marks between 40 and 60, 1, 0)) as '(40-60)'
FROM
tbl
GROUP BY
subject
我认为这样的事情可以工作......
SELECT t.`subject`,
(SELECT COUNT(*) FROM `subject` as t2 WHERE t2.`range` BETWEEN (10 AND 40) AND t2.`subject` = t.`subject`) as `range1040`,
(SELECT COUNT(*) FROM `subject` as t2 WHERE t2.`range` BETWEEN (40 AND 60) AND t2.`subject` = t.`subject`) as `range4060`
FROM `table` as t
GROUP BY t.`subject`
ORDER BY t.`subject`
select subject, sum(case when marks between 10 and 40 then 1 else 0) as oneToFourty,
sum(case when marks between 40 and 60 then 1 else 0) as fourtyToSixty
from table
group by subject
你的范围似乎有点奇怪(重叠),所以我会把更精细的细节留给你。
这有效:
select subject,
sum(case when marks between 10 and 40 then 1 else 0 end) as Range1,
sum(case when marks between 40 and 60 then 1 else 0 end) as Range2
from _Scores
group by subject
这是因为 case 语句将检查每一行,如果数字匹配则返回 Range1,否则返回 0。与 Range2 相同。sum 语句将 1 和 0 相加,为您提供每个计数。