[英]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_jobs
: city
、 state
、 occ_title
、 jobs_1000
和loc_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.