下面的SQL查询给出了我想要的结果,但使用CASE语句似乎不正确。 是否有另一种方法为过滤列创建别名?有没有更有效的方法来实现相同的结果?
以下是当前查询:
SELECT
year,
college_name,
count(id_999999999) as count_id_999999999,
count(id_999999999)/count(student_id) as percent_id_999999999,
count(id_other) as count_id_other,
count(id_other)/count(student_id) as percent_id_other,
count(student_id) as total_id
FROM (SELECT fiscal_year, semester,
CASE
WHEN student_id IN ('999999999') THEN 'id - 999999999'
END
AS id_999999999,
CASE
WHEN student_id NOT IN ('999999999') THEN 'id - Other'
END
AS id_other,
student_id
FROM enrolment_data) enrol
GROUP BY year, college_name
ORDER BY year, college_name;
以下是理想的结果:
答案 0 :(得分:1)
查询过于复杂。你不需要子查询。我会把查询写成:
SELECT year, college_name,
sum(case when student_id IN ('999999999') then 1 else 0 end) as count_id_999999999,
avg(case when student_id IN ('999999999') then 1.0 else 0 end) as percent_id_999999999,
sum(case when student_id NOT IN ('999999999') then 1 else 0 end) as count_id_other,
avg(case when student_id NOT IN ('999999999') then 1.0 else 0 end) as percent_id_other
count(*) as total_id
FROM enrolment_data ed
GROUP BY year, college_name
ORDER BY year, college_name;