如果每個語言的多個條目,要在結果每種語言只有一行,並仍希望按百分比排序,您可能希望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;
或合併DISTINCT
與window functions:
SELECT * FROM (
SELECT DISTINCT
language, max(percentage) OVER (PARTITION BY language) AS max_percent
FROM countrylanguage
) AS sub
ORDER BY max_percent DESC;
最後一個會在這種情況下,最慢的。
SELECT DISTINCT語言FROM countrylanguage ORDER BY percentage DESC; 錯誤:對於SELECT DISTINCT,ORDER BY表達式必須出現在選擇列表中 LINE 1:... T DISTINCT language FROM countrylanguage ORDER BY percentage ... –