我正在使用Postgres 9.1来尝试获取一些数据 我有三张(虚构/消毒)表:
Table "public.students"
Column | Type | Modifiers
--------------+-----------------------------+-----------
id | uuid | not null
name | character varying |
birth_date | date |
last_exam_at | timestamp without time zone |
created_at | timestamp without time zone |
code | character varying |
gender | character varying |
Indexes:
"students_id_key" UNIQUE CONSTRAINT, btree (id)
Referenced by:
TABLE "exams" CONSTRAINT "exams_student_id_fkey"
FOREIGN KEY (student_id) REFERENCES students(id)
Table "public.exams_essays"
Column | Type | Modifiers
----------+------+-----------
exam_id | uuid |
essay_id | uuid |
Table "public.exams"
Column | Type | Modifiers
-------------------+-----------------------------+-----------
id | uuid | not null
student_id | uuid |
created_at | timestamp without time zone |
completed_at | timestamp without time zone |
course | character varying |
Table "public.essays"
Column | Type | Modifiers
-----------------+-----------------------------+-----------
id | uuid | not null
essay_type | character varying | not null
filename | character varying |
我正在尝试获取以created_at::date
和student_id
分组的以下信息:
exam.course = 'history'
)exam.course = 'english'
)这些查询中的每一个都不是很难单独完成,但将它们放在一起证明是困难的。
答案 0 :(得分:1)
SELECT COUNT(DISTINCT EX.exam_id) TotalExams,
SUM(CASE WHEN E.course = 'history' THEN 1 ELSE 0 END) HistoryEssays,
SUM(CASE WHEN E.course = 'english' THEN 1 ELSE 0 END) EnglishEssays
FROM public.exams AS EX
LEFT JOIN public.exams_essays AS EE
ON EX.exam_id = EE.essay_id
答案 1 :(得分:1)
SELECT created_at::date, student_id
,count(*) AS exams
,sum(CASE WHEN course = 'history' THEN essays ELSE 0 END) AS essays_hist
,sum(CASE WHEN course = 'english' THEN essays ELSE 0 END) AS essays_engl
FROM public.exams x
LEFT JOIN (
SELECT exam_id AS id, count(*) AS essays
FROM public.exams_essays
GROUP BY exam_id
) s USING (id)
GROUP BY created_at::date, student_id;
我在连接之前聚合了n-table ,从而避免了行开头的乘法。使查询更简单(IMO)和更快。