简体   繁体   English

在PostgreSQL中从另一个表中减去一个表

[英]Subtracting one table from another in PostgreSQL

I have a table that contains student IDs and their GPA. 我有一张包含学生ID和GPA的表格。

_____________
| sID | GPA |
-------------
|  1  | 3.7 |
|  2  | 3.9 |
|  3  | 3.6 |
|  4  | 3.7 |
|  5  | 3.1 |
|  6  | 3.9 |

I wanted to create a table that gives me only the students who have the highest, or second highest GPAs. 我想创建一个表格,只给出GPA最高或次高的学生。 In other words, I want this result: 换句话说, 我想要这个结果:

_____________
| sID | GPA |
-------------
|  2  | 3.9 |
|  6  | 3.9 |
|  1  | 3.7 |
|  4  | 3.7 |

To do so, I began by writing a query that gives me all the students who match the highest score: 为此,我首先编写了一个查询,为我提供了所有匹配得分最高的学生:

SELECT * 
FROM gpaTable
WHERE gpa in (
      SELECT max(gpa) FROM gpaTable)

This gives me: 这给了我:

| sID | GPA |
-------------
|  2  | 3.9 |
|  6  | 3.9 |

To get the second highest as well, I want to subtract this result from the entire original table, and then repeat the query that finds the max again. 为了获得第二高,我想从整个原始表中减去此结果,然后重复再次找到max的查询。

I assume it would look something like this, however, I can't get it right. 我认为它看起来像这样,但是, 我无法做到这一点。

SELECT *
FROM gpaTable
WHERE gpa IN (
    SELECT * 
    FROM gpaTable
    WHERE gpa in (
          SELECT max(gpa) FROM gpaTable)
    )
 OR
    (SELECT *
     FROM gpaTable
     WHERE NOT EXISTS IN
           (SELECT * 
            FROM gpaTable
            WHERE gpa in (
            SELECT max(gpa) FROM gpaTable)
    )

In English, the query says (or should say) Give me every row that appears in the table of maximum GPAs OR in the table of maximum GPAs of the lesser GPAs 在英语中,查询说(或应该说) 给我最大GPA表中出现的每一行 在较小GPA的最大GPA表中

I'd really appreciate any help! 我真的很感激任何帮助!

Would it not be easier to just select the top 2 entries in the subselect? 选择subselect中的前2个条目会不容易? You could, eg, use LIMIT : 你可以,例如,使用LIMIT

SELECT * 
FROM gpaTable
WHERE gpa in (SELECT DISTINCT gpa FROM gpaTable ORDER BY gpa DESC LIMIT 2) ORDER BY gpa;

You can do it like this: 你可以这样做:

select *
from gpaTable
where gpa in (
  select distinct gpa
  from gpaTable
  order by gpa desc
  limit 2
)

The idea is similar to your first solution, except MAX is replaced with ordering and a LIMIT 2 这个想法类似于你的第一个解决方案,除了MAX被排序和LIMIT 2取代

Demo on sqlfiddle. 在sqlfiddle上演示。

SELECT sid, gpa
FROM (
   select sid, 
          gpa, 
          dense_rank() over (order by gpa desc) as rnk
   from gpaTable
) t
where rnk <= 2
order by sid;

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

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