-1

有没有办法通过您未在 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...
4

2 回答 2

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...什么?

于 2012-09-11T00:39:58.953 回答
1

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

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

如果您只希望每种语言有一个具有最大百分比的条目,则可以使用DISTINCT ON但要区分的列必须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;

或结合DISTINCT窗口函数

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

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

于 2012-09-11T02:34:06.993 回答