使用子查询查找给定日期最大值的行
Using a subquery to find rows given a max value of date
我有以下 table:
CREATE TABLE my_table
(
the_debt_id varchar(6) NOT NULL,
the_amount int NOT NULL,
the_debt_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)
但我得到的错误是 "more than one row returned by a subquery used as an expression"。请提供任何帮助,我们将不胜感激。
在 Postgres 中,您可以为此使用方便的扩展 distinct on
:
select distinct on (the_id) * from my_table order by the_id, the_date desc
SELECT * FROM my_table
WHERE the_debt_date in (SELECT MAX(the_debt_date)
FROM my_table GROUP BY the_debt_id)
当子查询return多条记录时使用in。
当您 101% 确定子查询将始终 return 只有一条记录时,使用 =。
我有以下 table:
CREATE TABLE my_table
(
the_debt_id varchar(6) NOT NULL,
the_amount int NOT NULL,
the_debt_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)
但我得到的错误是 "more than one row returned by a subquery used as an expression"。请提供任何帮助,我们将不胜感激。
在 Postgres 中,您可以为此使用方便的扩展 distinct on
:
select distinct on (the_id) * from my_table order by the_id, the_date desc
SELECT * FROM my_table
WHERE the_debt_date in (SELECT MAX(the_debt_date)
FROM my_table GROUP BY the_debt_id)
当子查询return多条记录时使用in。 当您 101% 确定子查询将始终 return 只有一条记录时,使用 =。