PostgreSQL-每个id的最大值

时间:2019-12-16 12:50:35

标签: sql postgresql

我正在尝试从表格检查中获取每种蛋白质的exam_id的最大值。

proteges

 protege_id | protege_patron | protege_firstname | protege_lastname
------------+----------------+-------------------+------------------
          1 |              1 | Andrzej           | Maniek
          2 |              1 | Anna              | Maj
          3 |              1 | Joanna            | Jankowska
exams

 exam_id | exam_protege | exam_weight | exam_glucose | exam_pressure
---------+--------------+-------------+--------------+---------------
       1 |            1 | 84          | 3ml          | 123/84
       2 |            1 | 99          | 23ml         | 124/72
       3 |            2 | 99          | 23ml         | 124/72
       4 |            3 | 94          | 23ml         | 124/72

首先我尝试过

SELECT DISTINCT protege_patron, exams.* 
FROM exams INNER JOIN proteges ON protege_id = exam_protege 
WHERE exam_id = (SELECT MAX(exam_id) FROM exams WHERE protege_patron = 1);

输出为:

 protege_patron | exam_id | exam_protege | exam_weight | exam_glucose | exam_pressure
----------------+---------+--------------+-------------+--------------+---------------
              1 |       4 |            3 | 94          | 23ml         | 124/72
(1 row)

尝试SELECT protege_firstname, protege_lastname, MAX (exam_id) FROM exams JOIN proteges ON protege_id = exam_protege GROUP BY protege_id;后,输出为:

 protege_firstname | protege_lastname | max
-------------------+------------------+-----
 Andrzej           | Maniek           |   2
 Anna              | Maj              |   3
 Joanna            | Jankowska        |   4
(3 rows)

因此,合理的方法是添加更多诸如exam_weight之类的东西 那就是我所做的:

SELECT protege_firstname, protege_lastname, exam_weight, MAX (exam_id) FROM exams JOIN proteges ON protege_id = exam_protege GROUP BY protege_id;
ERROR:  column "exams.exam_weight" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select protege_firstname, protege_lastname, exam_weight, MAX...
                                                    ^

自动取款机我不知道该如何解决。尝试过与众不同,阅读一些有关聚合函数的信息...有什么方法可以做到这一点?我要做的就是加入两个表,并为每个蛋白质选择他的所有值和他的考试值,最大max_id ...

2 个答案:

答案 0 :(得分:1)

您可以使用distinct on。我认为逻辑是:

select distinct on (exam_protege) e.*
from exams e
order by exam_protege, exam_id desc;

您当然也可以使用join引入蛋白质信息:

select distinct on (exam_protege) e.*, p.*
from exams e join
     protege p
     on e.exam_protege = p.protege_id
order by exam_protege, exam_id desc;

答案 1 :(得分:1)

您可以这样做:

select * from
(
  select max(exam_id) maxexamid, exam_protege from exams group by exam_protege
) as maxexams  
inner join proteges p
    on maxexams.exam_protege = p.protege_id
inner join exams e 
    on e.exam_id = maxexams.maxexamid