我正在尝试查询数据库,我认为我的查询可能会缩短以消除子查询,但我这样做的每次尝试都会导致某种错误(我对SQL有点新)。
该数据库按年龄和性别群体提供有关学校人口统计数据的信息。我试图通过以下查询获取有关性别的摘要信息:
SELECT i.id AS id,
(SELECT group_concat(entry separator '`')
FROM
(SELECT school_id,
concat(gender, '|', sum(percentage)) AS entry
FROM school_demographics
GROUP BY gender,
school_id) AS s1
WHERE s1.school_id = i.id ) AS demographics
FROM school_info i
WHERE i.id = 500;
这样可行,并将我需要的所有内容合并到一个female|65.4`male|34.4
形式的字符串中
(正如我所愿),但我有这种感觉,不需要其中一个子查询,特别是我返回列AS entry
只在上面的group_concat中使用它。我是否认为有一种更简单的方法可以使此查询有效?
答案 0 :(得分:1)
结果必须为每个查询的id
返回一行
这并不意味着,它不能返回多个列。因此,您可以尝试条件聚合(假设female
列中只有male
和gender
):
SELECT school_id,
SUM(CASE gender WHEN 'female' THEN percentage END) as percentage_female,
SUM(CASE gender WHEN 'male' THEN percentage END) as percentage_male
FROM school_demographics
GROUP BY school_id
WHERE school_id = 500
结果如下:
school_id | percentage_female | percentage_male
500 | 65.4 | 34.4
答案 1 :(得分:0)
请注意,彼此连接的子查询可能性能较差
select i.id,group_concat(d.gender,'|',d.p separator '`')
from
(select school_id,gender,sum(percentage) as p
from school_demographics
group by school_id,gender
) d
join school_info i on i.id=d.school_id
group by i.id
where i.id=500;
where i.id=500
可以删除