sql - 从 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 附近的语法错误
任何帮助将不胜感激
解决方案
你需要选择一些东西。对于所有列:
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 ON
和ORDER BY
需要保持一致。
推荐阅读
- bash - 每当存在某个字符串时,将所有文件从文件夹 A 移动到 B
- sql - 为什么我会收到 ORA-00904:确定性函数索引的无效标识符?
- ios - 如何快速将 NSArray 合并到 NSMutableArray?
- mysql - 尽管语法看起来错误,为什么以下 SQL 查询仍然有效?
- tensorflow - 我可以使用`tf.contrib.seq2seq.dynamic_decode`来替换encoder-decoder框架中的函数`tf.nn.dynamic_rnn`吗?
- debugging - IBM System i - 用于 RDi 调试的调试服务器不起作用
- class - Tensorflow中连体模型中子类的共享权重
- coq - Coq 影响分析
- sql - 在 Redshift sql 上对时间间隔进行分组
- mysql - MySQL 服务器:仅将一些数据库移动到另一个位置