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
答案 0 :(得分:1)
使用派生表:
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)
答案 1 :(得分:1)
你也可以:
select max(id) as id, number
from test
group by number
order by id desc
limit 4