简体   繁体   English

PostgreSQL:SELECT 多列中整个表的最大数值

[英]PostgreSQL: SELECT MAX numeric value for entire table from multiple columns

I have a table similar to this (3 rows, 4 columns: id, name, gradeA, gradeB):我有一个类似的表(3行,4列:id,name,gradeA,gradeB):

id    name    gradeA    gradeB
------------------------------
1     David   59        78
2     Anna    66        92
3     David   22        89

I'm looking for a query that will give me 1 numeric property for the highest grade by in the whole table by condition.我正在寻找一个查询,它将按条件在整个表中为我提供最高等级的 1 个数字属性。 for example:例如:

What is the highest grade for any student named David?任何名叫大卫的学生的最高成绩是多少?

The answer should be { maxGrade: 89 }答案应该是 { maxGrade: 89 }

Note: grades are stored as varchar values and should be cast to numeric values for comparison注意:成绩存储为 varchar 值,应转换为数值以进行比较

You need to combine max() with greatest()您需要将max()greatest()结合起来

select max(greatest(gradea::int, gradeb::int)) as max_grade
from the_table
where name = 'David';

If you need a JSON result (because you wrote: result should be {maxGrade: 89} ), you can wrap that query and convert the row to JSON:如果您需要JSON结果(因为您写道:结果应该是 {maxGrade: 89} ),您可以包装该查询并将该行转换为 JSON:

select to_jsonb(t) 
from (
  select max(greatest(gradea::int, gradeb::int)) as "maxGrade"
  from the_table
  where name = 'David'
) t;

Try the below:试试下面的:

We shall achieve with GREATEST and MAX:我们将通过 GREATEST 和 MAX 实现:

  1. We can make use of GREATEST to return the large value between the columns grade A and grade B for every user record我们可以利用GREATEST返回每个用户记录的 A 级和 B 级列之间的大值
  2. And use MAX to return the maximum grade if more than user matches with the same name.如果有多个同名用户匹配,则使用MAX返回最高成绩。
SELECT 
  MAX(GREATEST(gradeA::integer, gradeB::integer)) as maxGrade 
FROM 
  "table_name" 
WHERE 
  "table_name"."name" = 'David';

I would recommend a lateral join:我建议横向连接:

select max(grade::int) as max_grade
from t cross join lateral
     (values (gradea), (gradeb)) v(grade)
where name = 'David';

In particular, this works if any of the grades are NULL .特别是,如果任何等级是NULL ,则此方法有效。

It can also easily be tweaked to get which grade is the maximum:它也可以很容易地调整以获得最高等级:

select v.*
from t cross join lateral
     (values ('a', gradea), ('b', gradeb)) v(which, grade)
where name = 'David'
order by grade::int desc
limit 1

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

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