使用子查询查找给定日期最大值的行

问题描述 投票:1回答:2

我有下表:

CREATE TABLE my_table 
(
    the_id varchar(6) NOT NULL, 
    the_amount int NOT NULL, 
    the_date date NOT NULL
)

INSERT INTO my_table
VALUES ('LMUS01', '200', '2/12/2019'), 
       ('LMUS01', '200', '2/11/2019'), 
       ('LMUS01', '300', '2/13/2019'), 
       ('LMUS02', '100', '2/10/2019'), 
       ('LMUS02', '150', '2/12/2019')

在这种情况下,我需要最大the_date中按the_id分组的行:

'LMUS01','300','2/13/2019'
'LMUS02','150','2/12/2019'

我尝试了以下查询:

SELECT * FROM my_table 
WHERE the_debt_date = (SELECT MAX(the_debt_date) 
FROM my_table GROUP BY the_debt_id)

但是我得到的错误是“由用作表达式的子查询返回的一行以上”。请,您能提供的任何帮助将不胜感激。

sql postgresql greatest-n-per-group
2个回答
2
投票

在Postgres中,您可以为此使用方便的扩展名distinct on

select distinct on (the_id) * from my_table order by the_id, the_date desc

0
投票
SELECT * FROM my_table 
WHERE the_debt_date in (SELECT MAX(the_debt_date) 
FROM my_table GROUP BY the_debt_id)
当子查询返回多条记录时,

使用in。当您确定101%的子查询将始终只返回一个记录时,请使用=

© www.soinside.com 2019 - 2024. All rights reserved.