简体   繁体   English

从子集中获取最大值的 SQL 查询

[英]SQL Query for max value from subsets

I have a table bls_jobs with the following columns: city , state , occ_title , jobs_1000 , and loc_quotient我有一个bls_jobs以下列的表bls_jobscitystateocc_titlejobs_1000loc_quotient

I am trying to retrieve the highest loc_quotient for each city (each city has several occ_titles , and each occ_title has a loc_quotient )我正在尝试为每个城市检索最高的loc_quotient (每个城市都有几个occ_titles ,每个occ_title都有一个loc_quotient

Currently, I can use this query:目前,我可以使用这个查询:

SELECT *
FROM bls_jobs
WHERE city = 'Hattiesburg'
ORDER BY loc_quotient DESC
LIMIT 1

Which does return what I'm looking for (the highest loc_quotient in the city, with each of the columns returned), but I'm struggling to figure out how to have it do this for all cities so I have a returned output of just each city's highest loc_quotient along with it's data from the other columns ...这确实返回了我正在寻找的东西(城市中最高的loc_quotient ,每一列都返回了),但我正在努力弄清楚如何让它对所有城市都这样做,所以我的返回输出只是每个城市的最高loc_quotient以及来自其他列的数据......

Use distinct on : distinct on使用distinct on

SELECT DISTINCT ON (j.city) j.*
FROM bls_jobs j
ORDER BY j.city, j.loc_quotient DESC;

DISTINCT ON is a convenient Postgres extension. DISTINCT ON是一个方便的 Postgres 扩展。 It returns the first row in each group, where groups are the keys in the DISTINCT ON () clause (and the ORDER BY is consistent with them).它返回每个组中的第一行,其中组是DISTINCT ON ()子句中的键(并且ORDER BY与它们一致)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM