gpt4 book ai didi

postgresql - 使用 distinct on 分组时无法正确排序结果

转载 作者:行者123 更新时间:2023-11-29 14:36:16 25 4
gpt4 key购买 nike

CREATE  TABLE test(
id integer,
content text,
number integer
)

INSERT INTO test(id,content,number) VALUES(1,'a'::text, 5);
INSERT INTO test(id,content,number) VALUES(2,'b'::text, 2);
INSERT INTO test(id,content,number) VALUES(3,'c'::text, 2);
INSERT INTO test(id,content,number) VALUES(4,'d'::text, 3);
INSERT INTO test(id,content,number) VALUES(5,'e'::text, 1);
INSERT INTO test(id,content,number) VALUES(6,'f'::text, 3);
INSERT INTO test(id,content,number) VALUES(7,'g'::text, 3);
INSERT INTO test(id,content,number) VALUES(8,'h'::text, 2);
INSERT INTO test(id,content,number) VALUES(9,'i'::text, 4);

我想要的是,将数字列分组并以 id 列作为 desc 对结果进行排序,如下所示;

| id | number
----------------
| 9 | 4
| 8 | 2
| 7 | 3
| 5 | 1

在这里,所有多次出现的数字(如 2,3 和 1)都被分组并且只出现一次,并且还按 id 列 desc 排序。

我试过这个查询,但它对我不起作用;

SELECT DISTINCT ON (number) number, id FROM test  ORDER  BY number,id DESC LIMIT 4

最佳答案

使用派生表:

SELECT id, number
FROM (
SELECT DISTINCT ON (number) number, id
FROM test
ORDER BY number, id DESC
) s
ORDER BY id DESC
LIMIT 4;

id | number
----+--------
9 | 4
8 | 2
7 | 3
5 | 1
(4 rows)

关于postgresql - 使用 distinct on 分组时无法正确排序结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44260317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com