简体   繁体   English

在另一个查询中使用一个查询的结果

[英]use the result from one query in another query

I am very new to postgresql. 我对Postgresql很陌生。 I have a table which looks like this 我有一张看起来像这样的桌子

NAME GPA SUBJECT
BEN 3.5 MATH
BEN 3.7 BIOLOGY
KATE 3.7 MATH
KATE 3.7 BIOLOGY

one query gives me the average gpa for everyone for all subjects. 一个查询可以给我所有科目的每个人的平均GPA。

select avg(gpa) from table;

result: 结果:

AVGALLGPA
3.8

another query gives the average gpa for each person. 另一个查询给出每个人的平均gpa。

select avg(gpa) from table group by name;

result: 结果:

NAME AVGGPA
BEN 3.78
KATE 3.83

now I am writing a query which counts how many students have avg better than overall avg. 现在,我正在编写一个查询,该查询计算出有多少学生的平均成绩好于整体平均成绩。

select 
    count(case when avg(gpa)> avgallgpa then 1 
          else null end) 
from table;

how can I pass the result(the avgallgpa) from the previous query into the later query? 如何将前一个查询的结果(avgallgpa)传递到后一个查询?

 select count(*) from (
    select name from the_table 
    group by name
    having avg(gpa) > (select avg(gpa) from the_table )
) t

You could use a Sub-query. 您可以使用子查询。

select COUNT(*) from table 
group by name having 
avg(gpa) > (select avg(gpa) from table);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM