2012-09-11 62 views
-1

有沒有辦法通過一些命令你的表,你不選擇條款,如選擇:ORDER BY與PostgreSQL的

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; 

給出了這樣的錯誤消息:

​​
+0

SELECT DISTINCT語言FROM countrylanguage ORDER BY percentage DESC; 錯誤:對於SELECT DISTINCT,ORDER BY表達式必須出現在選擇列表中 LINE 1:... T DISTINCT language FROM countrylanguage ORDER BY percentage ... –

回答

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...做?

+0

好吧,這是有效的,我看我的表錯了,因爲我的表中有多種語言對應於不同的國家或地區,所以這就是爲什麼我把DISTINCT放在那裏,但我忘記了不同的地區可能包含相同的語言。謝謝 –

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,但對被不同的列來首位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 

或者使用與不同的路線:

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; 

最後一個會在這種情況下,最慢的。