我想检索基于max(created)的emp detail table grouping by class_uno的所有数据。另外,我不想按数据与任何其他列分组,因为它会更改最终结果。
此外,是否有任何解决方案可以在不使用GROUPBY子句的情况下检索相同的结果

create table emp
(
   emp_id serial primary key,
   emp_no integer,
   emp_ref_no character varying(15),
   emp_class character varying(15),
   created_at timestamp,
   created_by character varying(20)
);

create table emp_detail
(
   emp_detail_id serial primary key,
   emp_id integer,
   class_no integer,
   col1 JSONB,
   col2 JSONB,
   col3 JSONB,
   created_at timestamp without time zone default now(),
   created_by character varying(20),
   constraint con_fk foreign key(emp_id) references emp(emp_id)
 );

INSERT INTO emp(
            emp_no, emp_ref_no, emp_class, created_by)
    VALUES ('548251', '2QcW', 'abc', 'Nik');

INSERT INTO emp_detail(
            emp_id, class_no, created_at,
            created_by)
    VALUES ( 1, 1, '2018-05-04 11:00:00',
            'Nik');

INSERT INTO emp_detail(
            emp_id, class_no, created_at,
            created_by)
    VALUES ( 1, 1, '2018-04-04 11:00:00',
            'Nik');

INSERT INTO emp_detail(
            emp_id, class_no, created_at,
            created_by)
    VALUES ( 1, 2, '2018-05-10 11:00:00',
            'Nik');

INSERT INTO emp_detail(
            emp_id, class_no, created_at,
            created_by)
    VALUES ( 1, 2, '2018-02-01 11:00:00',
            'Nik');

最佳答案

我想你想要:

select distinct on (ed.class_no) ed.*
from emp_detail ed
order by ed.class_no, created_at desc;

distinct on是一个非常方便的Postgres扩展。这可能是最快的方法,尤其是索引在distinct on上时。
其他可选方法是带有emp_detail(class_no, created_at desc)的子查询或相关子查询。

10-06 06:19