我有一个像下面这样的表,
如何编写查询以获取此
答案 0 :(得分:4)
您没有指定正在使用的数据库产品,但您应该能够在任何数据库中使用带有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;
答案 1 :(得分:3)
尝试此查询
对于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
答案 2 :(得分:0)
我觉得这样的事情可以奏效......
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`
答案 3 :(得分:0)
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
你的范围似乎有点奇怪(重叠)所以我会给你留下更精细的细节。
答案 4 :(得分:0)
这有效:
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相加,以给出每个的计数。