首页 > 解决方案 > 从 PostgreSQL 中的一组 id 中选择第一个元素

问题描述

我有下表:

CREATE TABLE my_table 
(
    the_debt_transact_id int NOT NULL,
    the_debt_id varchar(6) NOT NULL, 
    the_amount int NOT NULL, 
    the_debt_date date NOT NULL,
    the_debt_flag varchar(6)
)

INSERT INTO my_table
VALUES ('900004','LMUS01', '200', '2/12/2019','NORMAL'), 
       ('900002','LMUS01', '200', '2/11/2019','NORMAL'), 
       ('900005','LMUS01', '300', '2/13/2019','RESCHE'), 
       ('900001','LMUS02', '100', '2/10/2019','NORMAL'), 
       ('900003','LMUS02', '150', '2/12/2019','NORMAL')

我希望每个债务 id 的第一个元素按交易编号降序排列,但它的标志不是“RESCHE”。

这是预期的输出:

the_debt_transact_id    the_debt_id    the_amount    the_debt_date    the_debt_flag 
900004                  LMUS01         200           2/12/2019        NORMAL
900003                  LMUS02         150           2/12/2019        NORMAL

我试过:

SELECT DISTINCT ON(the_debt_id) 
FROM my_table 
WHERE the_debt_id IN ('LMUS01','LMUS02') 
AND the_debt_flag <> 'RESCHE' 
ORDER BY the_debt_transact_id DESC 

但它返回了我

FROM 附近的语法错误

任何帮助将不胜感激

标签: sqlpostgresql

解决方案


你需要选择一些东西。对于所有列:

SELECT DISTINCT ON (the_debt_id) t.*
FROM my_table t
WHERE the_debt_id IN ('LMUS01','LMUS02') AND the_debt_flag <> 'RESCHE'
ORDER BY the_debt_idl, the_debt_transact_id DESC ;

注意DISTINCT ONORDER BY需要保持一致。


推荐阅读