Sql 如何通过仅使用一列进行分组来选择多个列

Sql 如何通过仅使用一列进行分组来选择多个列,sql,postgresql,Sql,Postgresql,我想根据max(created_at)检索emp detail表分组的所有数据。另外,我不想将数据分组到任何其他列,因为它会更改最终结果。 另外,是否有任何解决方案可以在不使用GROUPBY子句的情况下检索相同的结果 create table emp ( emp_id serial primary key, emp_no integer, emp_ref_no character varying(15), emp_class character varying(15),

我想根据max(created_at)检索emp detail表分组的所有数据。另外,我不想将数据分组到任何其他列,因为它会更改最终结果。 另外,是否有任何解决方案可以在不使用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扩展。这可能是最快的方法,尤其是在
emp\u detail(class\u no,created\u at desc)
上有索引时


其他选择是带有
行号()的子查询。
或相关子查询。

你真是天才!