我创建了一个表格,如下所示:
CREATE TABLE myRecord(stu_name VARCHAR(50),gender VARCHAR(50),level VARCHAR(50));
INSERT INTO myRecord VALUES('John','Male','Pre-Primary');
INSERT INTO myRecord VALUES('Jane','Female','Year 1');
INSERT INTO myRecord VALUES('Sue','Female','Year 2');
预期结果应该如下:
Male | Female | Level
----------------------
1 | 0 | Pre-Primary
但是当我运行下面的SQL时:
SELECT SUM(t.Male) AS Male,
SUM(t.Female) AS Female,
t.level
FROM
((SELECT SUM(gender='Male') as Male,
SUM(gender='Female') as Female,
CASE WHEN level='Pre-Primary'
THEN 'Pre-Primary'
END AS level
FROM myRecord
) t)
;
输出如下:
Male | Female | Level
----------------------
1 | 2 | Pre-Primary
它还计算了第1年和第2年。我只希望它计算level ='Pre-Primary'的级别的每个性别。我尝试过使用GROUP BY级别,但它给了我相同的结果。我也试过了,但它给了我一个错误。
有没有可行的方法呢?我已经在这方面工作了好几天,但我无法解决它,这有点令人失望。我希望有人可以帮忙解决这个问题。
答案 0 :(得分:2)
也许你想要一个where
条款:
SELECT SUM(gender = 'Male') AS Male, SUM(gender = 'Female') AS Female, level
FROM myRecord
WHERE level = 'Pre-Primary';
我不明白为什么需要子查询。