将某些行分组然后GROUP BY一列

时间:2014-11-05 05:46:06

标签: mysql group-by rows

我有一个表名myrecord:

stu_name | gender | level
-------------------------
John     | Male   | Pre-Primary
Jane     | Female | Year 1
Sue      | Female | Year 2

我想将GROUP 1年级和2年级作为小学。我尝试过以下代码,但它无效。

SELECT
SUM(gender = 'Male') male,
SUM(gender = 'Female') female,
(
substr(level, Year 1, Year 2) as Primary,  
substr(level, Pre-Primary) as Pre-Primary)
as level
FROM myrecord
GROUP BY level

预期结果将是:

Male | Female | level 
-------------------------
1    | 0      | Pre-Primary
0    | 2      | Primary

有可能实现这一目标吗?我也试过使用CONCAT,但它也没有用。我真的需要帮助!

4 个答案:

答案 0 :(得分:0)

SELECT
SUM(gender = 'Male') male,
SUM(gender = 'Female') female,
(  substr(level, Year 1, Year 2) as Primary,
substr(level, Pre-Primary) as Pre-Primary)  as level
FROM myrecord
GROUP BY level

您可以使用案例来确定这是男性还是女性,并使用count而不是sum来计算该级别的男性。这是查询

未经过测试

SELECT
(case when gender='male' then Count(select gender from table where gender='Male') else 0 end) male,
(case when gender='female' then Count(select gender from table where gender='female') else 0 end) female,
(  case when level='Pre-primary' then level else 'Primary' end) as Primary
FROM myrecord
GROUP BY level

如果有错误,请告诉我,我没有测试

答案 1 :(得分:0)

查询

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'
WHEN level LIKE 'Year%'
THEN 'Primary'
ELSE NULL END AS level
FROM myRecord
GROUP BY level) t)
GROUP BY t.level;

Fiddle demo

答案 2 :(得分:0)

请尝试以下

SELECT SUM(CASE WHEN gender = 'MALE' THEN 1 ELSE 0 END) as Male, SUM(CASE WHEN gender = 'FEMALE' THEN 1 ELSE 0 END) as Female, CASE WHEN level='Primary' THEN 'Primary' ELSE 'Pre-Primary' END as newlevel FROM myrecord GROUP BY newlevel 

答案 3 :(得分:0)

SELECT
SUM(gender = 'Male') AS male,
SUM(gender = 'Female') AS  female,
(case when(level = 'Year 1' OR level = 'Year 2' ) then 'Primary' else 'Pre-Primary' end) AS tempLevel

FROM myrecord
GROUP BY tempLevel

这里我使用case语句检查myrecord表中的级别