如何获得MySQL中的学生数量

时间:2014-03-09 08:11:10

标签: mysql sql

如何使用MySQL获取不同类别学生的数量 我在st_category字段中有6个类别,在表格中有st_handi字段下有1个类别 - 在st_category => GEN,SC,ST,OBC,SGC,EWS和es_handi => PH

我需要从性别明智的每个类别的学生数量。实施例

       Male  | Female
      -------|-------
 GEN  | 54   |  239
 SC   | 19   |  9
 ST   | 5    |  19
 SGC  | 0    |  13
 OBC  | 19   |  9
 EWS  | 0    |  1
 PH   | 2    |  0

我试过可能尝试达到理想的输出但是每次尝试都会失望。

这可能吗?

学生表的模式

 ST_No | ST_Gender | ST_Category | ST_PH
 ------|-----------|-------------|-------
   1   | Male      | GEN         | Yes
   2   | Male      | GEN         | No
   3   | Female    | SC          | No
   4   | Male      | GEN         | No
   5   | Male      | ST          | No
   6   | Female    | GEN         | No
   7   | Male      | SC          | No

以上是表格的样本数据和架构。

4 个答案:

答案 0 :(得分:1)

从这样的事情开始:

SELECT Sum(Male) AS SumOfMale
FROM Students
GROUP BY Type;

答案 1 :(得分:0)

如果没有看到你的桌面结构我肯定不知道,但从你的描述来看,你的类别听起来像是在两个领域。我将假设这些字段在同一个表中?如果要将结果限制为仅这些类别,则只需要WHERE子句。

SELECT st_category AS cat, st_gender, COUNT(studentPK)
FROM es_preadmission
WHERE st_category IN ('GEN','SC','ST',....,'SGC')
GROUP BY st_category, st_gender
UNION ALL
SELECT st_handi AS cat, st_gender, COUNT(studentPK)
FROM es_preadmission
WHERE st_handi = 'PH'
GROUP BY st_handi, st_gender

答案 2 :(得分:0)

查询的第一部分计算由ST_Category分组的男性和女性,第二部分添加PH的总数,因为PH不是类别而只是标志。 (在第一个查询中我添加了条件Table.PH ='No',而不是在第二个查询Table.PH ='是'

试试这个:

SELECT 
    ST_category,
    SUM(
    CASE
        WHEN ST_Gender = 'Male'
        THEN 1
        ELSE 0
    ) as Male,
    SUM(
    CASE
        WHEN ST_Gender = 'Female'
        THEN 1
        ELSE 0
    ) as Female
FROM Table
WHERE Table.PH = 'No'
GROUP BY ST_category

UNION ALL

SELECT 
    'PH',
    SUM(
    CASE
        WHEN ST_Gender = 'Male'
        THEN 1
        ELSE 0
    ) as Male,
    SUM(
    CASE
        WHEN ST_Gender = 'Female'
        THEN 1
        ELSE 0
    ) as Female
FROM Table
WHERE Table.PH = 'Yes'

答案 3 :(得分:0)

希望这会有所帮助...... 例如一些像这样的表

CREATE TABLE students(
id SMALLINT NOT NULL AUTO_INCREMENT,
name VARCHAR(32),
gender VARCHAR(32),
category VARCHAR(32),
PRIMARY KEY(id)
);

我会做这样的事情

SELECT gender, category, COUNT(gender), COUNT(category) 
FROM students GROUP BY category, gender

sqlfiddle here