使用PostgreSQL进行ORDER BY

时间:2012-09-11 00:30:53

标签: sql postgresql sql-order-by

有没有办法按照您在select子句中未选择的内容来订购表格,例如:

Table Example

   Column  |    Type   |
-----------+-----------+
language   | character |
percentage | real      |
id         | integer   |

所以我想理想地做这样的事情

SELECT DISTINCT language FROM Example ORDER BY percentage DESC;

但这显然不起作用。有没有一种方法可以实际让它按百分比排序,而不在SELECT子句中实际选择百分比?

此查询

SELECT DISTINCT language 
FROM countrylanguage 
ORDER BY percentage DESC; 

给出了以下错误消息:

ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...T DISTINCT language FROM countrylanguage ORDER BY percentage...

2 个答案:

答案 0 :(得分:2)

您无需选择要对其进行排序的列。

create table language_pct (
  id integer primary key,
  language varchar(15) not null,
  percentage real not null,
  unique (language)
);

insert into language_pct values
(1, 'English', 15.3),
(2, 'French', 32.108),
(3, 'Russian', 12.88);

select language
from language_pct
order by percentage desc;

French
English
Russian

如果您有两行英语,每行都有不同的百分比,那么dbms会为select distinct...做些什么?

答案 1 :(得分:1)

如果每种语言有多个条目,但结果中每种语言只需要一行,并且仍希望按百分比排序,则可能需要GROUP BY language并使用sum()汇总百分比(或另一个aggregate function,具体取决于您的实际数据):

SELECT language, sum(percentage) AS total_percentage
FROM   countrylanguage
GROUP  BY language
ORDER  BY total_percentage DESC;

如果您只想使用最大百分比的每种语言一个条目,则可以使用DISTINCT ON但是不同的列有< / em>在ORDER BY子句中排在第一位:

SELECT DISTINCT ON (language)
       language, percentage
FROM   countrylanguage
ORDER  BY language, percentage DESC;

关于DISTINCT ON

要按语言排序,您必须将其放入子查询中:

SELECT * FROM (
   <query from above>
   ) AS sub
ORDER  BY percentage DESC, language; -- language only serves as tiebreaker

或使用与GROUP BY不同的路线:

SELECT language, max(percentage) AS max_percentage
FROM   countrylanguage
GROUP  BY language
ORDER  BY max_percentage DESC;

或将DISTINCTwindow functions结合使用:

SELECT * FROM (
   SELECT DISTINCT
          language, max(percentage) OVER (PARTITION BY language) AS max_percent
   FROM   countrylanguage
   ) AS sub
ORDER  BY max_percent DESC;

在这种情况下,最后一个将是最慢的。