我正在尝试使用PostgreSQL创建报告,其中列出了医生,特定问题的评分数量以及这些评分的平均值作为一条记录。
我进行了以下简单查询:
select p.token, count(r.id), avg(a.val)
from xx.tb1 r
inner join xx.tb2 p using (id)
inner join xx.tb3 a using (id)
where a.question_id = 1
group by token
将连续的question_id添加到查询中,最有效的方法是什么?我可以在多个select语句中使用相同的简单查询,但这似乎不是最有效的方法。工会不起作用,因为我希望按医生对数据进行分组。
谢谢!
您应该简单地将question_id添加为一列。然后,如果有问题,每个医生的行数将尽可能多。
select p.token, a.question_id, count(r.review_id), avg(a.val_num_raw)
from xx.review r
inner join xx.predicate p using (predicate_id)
inner join xx.answer a using (review_id)
group by token, a.question_id
编辑根据下面的评论,您应该A)在Excel之类的工具中旋转数据(或使用可以作为功能部件进行旋转的MS SQL 2012),或B)建立一个如下所示的可怕查询:
select q1.token, q1.cnt, q1.av, q2.cnt, q2.av, ...
FROM (
select p.token, count(r.review_id) as cnt, avg(a.val_num_raw) as av
from xx.review r
inner join xx.predicate p using (predicate_id)
inner join xx.answer a using (review_id)
where question_id = 1
group by token) q1
LEFT JOIN (
select p.token, count(r.review_id) as cnt, avg(a.val_num_raw) as av
from xx.review r
inner join xx.predicate p using (predicate_id)
inner join xx.answer a using (review_id)
where question_id = 2
group by token) q2 using (token)
LEFT JOIN (
select p.token, count(r.review_id) as cnt, avg(a.val_num_raw) as av
from xx.review r
inner join xx.predicate p using (predicate_id)
inner join xx.answer a using (review_id)
where question_id = 3
group by token) q3 using (token)
我将重点介绍一下,因为此查询的性能将非常糟糕。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句