我是Postgres和数据库的新手,所以很抱歉。我进行了查询,以从一张表中获得每所学校的学生人数。现在我有了下表:
school_probs:
school_code(PK bigint) schoolName(text) probs(numeric)
1 CAA {0.05,0.08,0.18,0.3,0.11,0.28}
2 CAS {0.06,0.1,0.295,0.36,0.12,0.065}
3 CBA {0.05,0.11,0.35,0.32,0.12,0.05}
4 CL {0.07,0.09,0.24,0.4,0.06,0.09}
我该如何将每个学校的计数乘以“概率”列中的每个数字。例如:我们在学校“ CAA”的学生总数为198,则概率分布为
(0.05*198, 0.08*198, 0.18*198, 0.3*198, 0.11*198, 0.28*198)
。有了结果,我就可以给学生评分。
我要获取计数的查询如下:
SELECT simulated_records.school, COUNT(simulated_records.school) as studentCount INTO CountSchool
FROM simulated_records, school_probs
WHERE simulated_records.school = school_probs.school
GROUP BY simulated_records.school;
答案 0 :(得分:3)
要将一个数组中的元素与一个常数相乘,您需要取消嵌套,相乘和聚合。有一些警告需要等待。考虑:
最好使用ARRAY constructor。
话虽如此,并就您未公开的表设计做出一些假设,但我还将简化计数:
到达:
SELECT *, ARRAY(SELECT unnest(p.probs) * r.student_ct) AS scaled_probs
FROM school_probs p
LEFT JOIN (
SELECT school, COUNT(*)::int AS student_ct
FROM simulated_records
GROUP BY 1
) r USING (school);
或者,将NULL数组表示为NULL数组:
SELECT *
FROM school_probs p
LEFT JOIN (
SELECT school, COUNT(*)::int AS student_ct
FROM simulated_records
GROUP BY 1
) r USING (school)
LEFT JOIN LATERAL (
SELECT ARRAY(SELECT unnest(p.probs) * r.student_ct) AS scaled_probs
) p1 ON p.probs IS NOT NULL;
db <>提琴here
我建议这种简单形式仅在Postgres 10或更高版本的SELECT列表中带有一个set-returning函数,因为: