Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 使用distinct on进行分组时无法正确排序结果_Postgresql_Grouping_Postgresql 9.6 - Fatal编程技术网

Postgresql 使用distinct on进行分组时无法正确排序结果

Postgresql 使用distinct on进行分组时无法正确排序结果,postgresql,grouping,postgresql-9.6,Postgresql,Grouping,Postgresql 9.6,我想要的是,将数字列和排序结果分组,并将id列作为desc,如下所示 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,

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

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);
在这里,所有具有多个外观(如2、3和1)的数字都被分组并仅显示一次,并且还与
id
column desc一起排序

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

| id | number
----------------
| 9  |    4
| 8  |    2
| 7  |    3
| 5  |    1
使用派生表:

SELECT DISTINCT ON (number) number, id FROM test  ORDER  BY number,id DESC LIMIT 4
使用派生表:

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)
您还可以:

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)

只是好奇而已。嗯,如果没有任何索引,如果您有“许多”记录(对于较小的表,您不会感觉到差异),那么在性能方面应该会更好。若使用适当的索引(比如:
…on test(number,id DESC)
),那个么对于小于1000万条记录(1000万条记录只是非常近似的数字),性能可能几乎相同。对于更多行,这应该表现得更好。只是出于好奇。嗯,如果没有任何索引,如果您有“许多”记录(对于较小的表,您不会感觉到差异),那么在性能方面应该会更好。若使用适当的索引(比如:
…on test(number,id DESC)
),那个么对于小于1000万条记录(1000万条记录只是非常近似的数字),性能可能几乎相同。对于更多行,这应该表现得更好。