使用 distinct on 分组时无法正确排序结果
can not order results properly when grouping with distinct on
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
列描述排序。
我试过这个查询,但它对我不起作用;
SELECT DISTINCT ON (number) number, id FROM test ORDER BY number,id DESC LIMIT 4
使用派生的 table:
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)
您还可以:
select max(id) as id, number
from test
group by number
order by id desc
limit 4
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
列描述排序。
我试过这个查询,但它对我不起作用;
SELECT DISTINCT ON (number) number, id FROM test ORDER BY number,id DESC LIMIT 4
使用派生的 table:
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)
您还可以:
select max(id) as id, number
from test
group by number
order by id desc
limit 4