我有下表:
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 但它会回报我
语法错误
如有任何帮助,将不胜感激。
发布于 2020-07-22 02:15:37
你需要选择一些东西。关于所有栏目:
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必须是一致的。
https://stackoverflow.com/questions/63025767
复制相似问题