格式化SQL表删除0并根据年份对它们进行分组

时间:2017-04-14 05:04:50

标签: mysql sql sql-server

我有一张表格,我想格式化。用于表的查询是

select x.year,
round(avg(case when c.mark >= 50 and x.term = 'S1' then 1 else 0 
end)::numeric,2) as s1_pass_rate,
round(avg(case when c.mark >= 50 and x.term = 'S2' then 1 else 0 
end)::numeric,2) as s2_pass_rate
from course_enrolments c join
courses s
on c.course = s.id
join semesters x on s.semester = x.id
where s.subject in (select id from subjects where name = 'COMP SYS') and 
c.mark IS NOT NULL
group by x.year, x.term;

它生成下表:

year | s1_pass_rate | s2_pass_rate
------+--------------+--------------
2003 |         1.00 |         0.00
2003 |         0.00 |         1.00
2004 |         1.00 |         0.00
2004 |         0.00 |         0.85
2005 |         1.00 |         0.00
2005 |         0.00 |         1.00
2006 |         1.00 |         0.00
2006 |         0.00 |         1.00

我想将其格式化为:

year | s1_pass_rate | s2_pass_rate
------+--------------+--------------
03 |         1.00 |         1.00
04 |         1.00 |         0.85
05 |         1.00 |         1.00
06 |         1.00 |         1.00

不确定如何对这些年份进行分组并删除0.00的值。请帮我解决一下这个。感谢

1 个答案:

答案 0 :(得分:0)

您可以尝试按年份(而不是术语)进行分组,然后获取两个合格率列中的每一列的总和。在该求和中,零将实际上为无操作,从而为您提供所需的非零值。请尝试以下查询:

SELECT RIGHT(CONVERT(varchar(4), t.year), 2)
       SUM(t.s1_pass_rate) AS s1_pass_rate,
       SUM(t.s2_pass_rate) AS s2_pass_rate
FROM
(
    SELECT x.year,
           ROUND(AVG(CASE WHEN c.mark >= 50 AND x.term = 'S1'
                              THEN 1 ELSE 0 END)::NUMERIC, 2) AS s1_pass_rate,
           ROUND(AVG(CASE WHEN c.mark >= 50 AND x.term = 'S2'
                              THEN 1 ELSE 0 END)::NUMERIC, 2) AS s2_pass_rate
    FROM course_enrolments c
    INNER JOIN courses s
        ON c.course = s.id
    INNER JOIN semesters x
        ON s.semester = x.id
    WHERE s.subject in (SELECT id FROM subjects WHERE name = 'COMP SYS') AND
          c.mark IS NOT NULL
    GROUP BY x.year, x.term
) t
GROUP BY t.year