单个查询的多个计数条件

时间:2013-09-05 19:06:17

标签: sql

我有一张如下表 -

Student ID | History | Maths | Geography
1               A        B         B     
2               C        C         E
3               D        A         B
4               E        D         A

如何通过单个SQL查询找出有多少学生在历史中获得A,在数学中获得B,在地理中获得E?

3 个答案:

答案 0 :(得分:3)

如果您希望获得在一栏中获得历史A的学生人数,则在第二栏获得数学学士学位的学生人数和在第三栏获得E的学生人数:

select
    sum(case when [History] = 'A' then 1 else 0 end) as HistoryA,
    sum(case when [Maths] = 'B' then 1 else 0 end) as MathsB,
    sum(case when [Geography] = 'E' then 1 else 0 end) as GeographyC
from Table1

如果你想计算历史上有A的学生,数学中的B和地理中的E:

select count(*)
from Table1
where [History] = 'A' and [Maths] = 'B' and [Geography] = 'E'

答案 1 :(得分:2)

如果您想要独立计数,请使用:

SELECT SUM(CASE WHEN Condition1 THEN 1 ELSE 0 END) AS 'Condition1'
      ,SUM(CASE WHEN Condition2 THEN 1 ELSE 0 END) AS 'Condition2'
      ,SUM(CASE WHEN Condition3 THEN 1 ELSE 0 END) AS 'Condition3'
FROM YourTable

如果您想要一个计数使用多个条件:

SELECT COUNT(*)
FROM YourTable
WHERE Condition1
  AND Condition2
  AND Condition3

听起来你想要多个独立的计数:

SELECT SUM(CASE WHEN History = 'A' THEN 1 ELSE 0 END) AS 'History A'
      ,SUM(CASE WHEN Maths = 'B' THEN 1 ELSE 0 END) AS 'Maths B'
      ,SUM(CASE WHEN Geography = 'E' THEN 1 ELSE 0 END) AS 'Geography E'
FROM YourTable

答案 2 :(得分:0)

您可以尝试从多个选择语句中进行选择

SELECT t1.*, t2.*, t3.* FROM
(SELECT COUNT(*) AS h FROM students WHERE History = 'A') as t1,
(SELECT COUNT(*) AS m FROM students WHERE Maths = 'B') as t2,
(SELECT COUNT(*) AS g FROM students WHERE Geography = 'E') as t3