结合窗口功能和条件

时间:2018-09-06 01:32:56

标签: sql postgresql window-functions

考虑经典的“学生与班级多对多”关系,一个学生可以参加多个班级,一个班级包含多个学生。

CREATE TABLE students(
  id serial PRIMARY KEY,
  name text,
  gender text NOT NULL
);

CREATE TABLE schools(
  id serial PRIMARY KEY,
  name text,
);

CREATE TABLE classes(
  id serial PRIMARY KEY,
  name text,
  school_id integer NOT NULL REFERENCES schools (id)
);

CREATE TABLE students_classes(
  id serial PRIMARY KEY,
  class_id integer NOT NULL REFERENCES classes (id),
  student_id integer NOT NULL REFERENCES students (id),
);

总体查询要大得多-考虑到学校和其他因素增加了问题的复杂性。因此,我需要使用窗口函数来获取诸如total_students之类的东西。

我想要一个查询,让我了解所有班级,该班级的学生总数,所报名的男生人数和女生的人数。

class_id | n_students | n_guys | n_girls
____________________________________________
         |            |        |

到目前为止,我有以下几点,我可以帮助一些男孩和女孩吗?

SELECT 
  school_id,
  w.class_id,
  w.n_students,
  w.n_guys,
  w.n_girls
FROM schools
JOIN classes ON classes.school_id = schools.id
JOIN (
    c.id AS class_id,
    COUNT(*) OVER (PARTITION BY sc.class_id) AS n_students,
    {Something} AS n_guys,
    {Something} AS n_girls
  FROM students_classes AS sc
  JOIN classes AS c ON sc.class_id = c.id
) as w ON w.class_id = classes.id
WHERE school_id = 81;

2 个答案:

答案 0 :(得分:2)

您可以使用此功能,而无需使用Windows /分析功能

malefemale更改为students.gender列的文本值

SELECT 
  s.school_id,
  c.class_id,
  COUNT(*) AS n_students,
  SUM(CASE WHEN st.gender = 'male' THEN 1 ELSE 0 END) AS n_guys,
  SUM(CASE WHEN st.gender = 'female' THEN 1 ELSE 0 END) AS n_girls
FROM schools s
INNER JOIN classes c
ON c.school_id = schools.id
INNER JOIN students_classes sc
ON sc.class_id = classes.id
INNER JOIN students st
ON st.id = sc.student_id
WHERE s.school_id = 81
GROUP BY s.school_id, c.class_id
ORDER BY s.school_id, c.class_id;

答案 1 :(得分:1)

因为只使用id,所以不需要schools表。因此,此查询基本上是join s个条件聚合:

select c.school_id, c.id as class_id,
       count(*) AS n_students,
       sum( (st.gender = 'male')::int ) AS n_guys,
       sum( (st.gender = 'female')::int ) AS n_girls
from classes c join
     students_classes sc
     on sc.class_id = c.id join
     students st
     on st.id = sc.student_id
where c.school_id = 81
group by c.school_id, c.id
order by c.school_id, c.id;