简体   繁体   English

我如何获得每个外键的最小值

[英]How can i get the minimal value for each foreign key

Given the following table:给出下表:

student   discipline   mark
-------   ----------   ----
   1         math       5 
   1      phylosophy    4
   1      literature    3
   2         math       2
   2      phylosophy    5
   2      literature    5

What is the best way to get the minimal mark for each student?为每个学生获得最低分数的最佳方法是什么? (result should be [3,2]) (结果应该是 [3,2])

Use the MIN function.使用MIN function。

SELECT student, MIN(mark)
FROM result_table
GROUP BY student

If you need the discipline they got the lowest mark in you can do the following:如果你需要纪律,他们得到了最低分,你可以做到以下几点:

SELECT result_table.*
FROM result_table 
JOIN (SELECT student, MIN(mark) as min_mark
  FROM result_table
  GROUP BY student) lowest_result ON result_table.student = lowest_result.student 
AND result_table.mark = lowest_result.min_mark

This will show the results where the student had the lowest mark.这将显示学生得分最低的结果。 Note that this will return two rows for a student if they have the same lowest mark in multiple subject.请注意,如果学生在多个科目中的最低分数相同,这将为学生返回两行。 To avoid this you can add another MIN around the discipline and GROUP BY student and mark.为避免这种情况,您可以在学科和GROUP BY学生和标记周围添加另一个MIN

If you need the discipline as part of the output the following might be slightly faster than using a sub-select (because only a single scan over the table is necessary) but it will probably only show for larger tables.如果您需要将纪律作为 output 的一部分,则以下内容可能比使用子选择稍快(因为只需要对表进行一次扫描),但它可能只显示较大的表。

select student,
       discipline, 
       mark as lowest_mark
from (
   select student,
          discipline,
          mark,
          row_number() over (partition by student order by mark) as rn
   from the_table
) t
where rn = 1

It will always return exactly one row per student.它总是会为每个学生返回一行。 If there are two disciplines with the same mark, it's not defined which one will be taken.如果有两个学科具有相同的标记,则不确定将选择哪个学科。

If you do want to return multiple rows if the lowest mark occurs more than once, you can use this:如果最低标记多次出现,你确实想返回多行,你可以使用这个:

select student,
       discipline, 
       mark as lowest_mark
from (
   select student,
          discipline,
          mark,
          min(mark) over (partition by student) as min_mark
   from the_table
) t
where mark = min_mark

If you do not need the discipline, but only the lowest mark, then GavinCattell's first statement is the way to go.如果你不需要纪律,只需要最低分,那么 GavinCattell 的第一个声明就是通往 go 的道路。

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

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