一張表存儲了學生id,科目,分數三個字段,求每個學生60分以下與參加的總科目占比。(今天電腦不好用,圖片總是這樣)
其實一個count(*) filter 就可以查出來,但是沒用過PG的一個人竟然說我這么簡單的SQL查詢都不會,只是因為我沒有用嵌套查詢。回來總結了以下,自己想到了以下幾種方法(只查詢出了對應的數目沒有做除法):
--filter函數
select stu_id, count(*), count(*) filter (where score<60) as "不及格"
from sherry.agg_filter
group by stu_id
--使用case when
select stu_id, count(*), sum(case when score<60 then 1 else 0) as "不及格"
from sherry.agg_filter group by stu_id
--關聯查詢
select stu_id, count(*), (select count(*) as c from sherry.agg_filter b where a.stu_id = b.stu_id and b.score < 60) as t2
from sherry.agg_filter a
group by a.stu_id
--臨時表關聯
with raw as(
select stu_id, count(*) as c1 from sherry.agg_filter
where score < 60
group by stu_id
),
raw2 as(
select stu_id, count(*) as c2
from sherry.agg_filter
group by stu_id)
select b.stu_id, c1, c2
from raw a
right join raw2 b
on a.stu_id = b.stu_id