计算男性和女性的数量来自桌子的女性

时间:2014-03-05 15:39:11

标签: mysql sql

SELECT 
  student_class.acad_yr,
  (case when((students.gender = 'Male') then count(students.gender) end)) AS Male,
  (case when((students.gender = 'Female') then count(students.gender) end)) AS Female
FROM
  students
  INNER JOIN student_class ON (students.st_id = student_class.st_id)
WHERE
  student_class.acad_yr = '2013/2014' AND 
  left(student_class.class_id, 1) = '1'
GROUP BY
  student_class.acad_yr
ORDER BY
  students.surname,
  students.othername

我收到此错误:

  

您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以便在'then count(students.gender)结束附近使用正确的语法))AS Male,     (情况何时((students.gender ='Fem'在第3行

3 个答案:

答案 0 :(得分:0)

SELECT 
  student_class.acad_yr,
  (SELECT COUNT(*) FROM STUDENTS WHERE GENDER = 'Male' AND acad_yr = student_class.acad_yr) AS Male,
  (SELECT COUNT(*) FROM STUDENTS WHERE GENDER = 'Female' AND acad_yr = student_class.acad_yr) AS Female,
FROM
  students AS S
INNER JOIN student_class ON (S.st_id = student_class.st_id)
WHERE
  student_class.acad_yr = '2013/2014' AND 
  left(student_class.class_id, 1) = '1'
GROUP BY
  student_class.acad_yr
ORDER BY
  S.surname,
  S.othername

答案 1 :(得分:0)

试试这个:

SELECT 
  student_class.acad_yr,
  sum(case when students.gender = 'Male' then 1 else 0 end) AS Male,
  sum(case when students.gender = 'Female' then 1 else 0 end) AS Female,
FROM
  students
  INNER JOIN student_class ON (students.st_id = student_class.st_id)
WHERE
  student_class.acad_yr = '2013/2014' AND 
  left(student_class.class_id, 1) = '1'
GROUP BY
  student_class.acad_yr
ORDER BY
  student_class.acad_yr

我删除了您在ORDER BY中使用的列,因为它没有多大意义。

答案 2 :(得分:0)

试试这个: -

SELECT 
  student_class.acad_yr,
  case when students.gender='Male' then count(students.gender) end AS Male,
  case when students.gender='Female' then count(students.gender) end AS Female
FROM
  students
  INNER JOIN student_class ON (students.st_id = student_class.st_id)
WHERE
  student_class.acad_yr = '2013/2014' AND 
  left(student_class.class_id, 1) = '1'
GROUP BY
  student_class.acad_yr
ORDER BY
  students.surname,
  students.othername

希望它会对你有所帮助。