0

我有一张如下表,

在此处输入图像描述

如何编写查询以获取此信息

4

5 回答 5

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;

请参阅带有演示的 SQL Fiddle

于 2013-06-12T12:11:31.860 回答
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

SQL 小提琴

于 2013-06-12T12:11:27.803 回答
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`
于 2013-06-12T12:11:12.890 回答
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

你的范围似乎有点奇怪(重叠),所以我会把更精细的细节留给你。

于 2013-06-12T12:12:42.107 回答
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 相加,为您提供每个计数。

于 2013-06-12T12:18:37.727 回答