我是sql的新手并使用postgres 9.6,我有2个查询,我想将它们加入到1中。我想使用Count函数,按照我在这里完成的降序排序字段
第一次查询
select count(s.city)::text as most_topics,
city::text || ', ' || state::text AS location from streams s
group by (location) order by most_topics desc limit 5
第一个查询正是我想要的信息完全相同的顺序,问题是我需要做一个内连接并从第二个表中获取数据,我在这里做了。第二个查询获取了我需要的所有数据但是我不知道如何在第二个查询中使用 Count()函数,任何建议都会很棒。总结一下,第一个查询让我将我想要的数据减半,因为我需要在字段(城市和州)上加入第二个称为拉链的数据。第二个查询给了我所需的所有数据,但我似乎无法使用Count()函数。
第二次查询
select DISTINCT ON(s.city,s.state)s.city as location,
z.latitudes,z.statelong,z.longitudes,z.thirtylatmin,z.thirtylatmax
,z.longitudes,z.thirtylatmin,z.thirtylatmax,
z.thirtylonmin,z.thirtylonmax from streams s inner join zips z
on (s.city=z.city and s.state=z.state) where order by s.city,s.state desc limit 5
首次查询结果
答案 0 :(得分:1)
您可以使用CTE或子查询:
with l5 as (
select count(s.city)::text as most_topics,
city::text || ', ' || state::text AS location,
city, state
from streams s
group by city, state
order by most_topics desc
limit 5
)
select distinct on (l5.locatin) l5.location, l5.most_topics, z.*
from l5 join
zips z
on l5.city = z.city and l5.state = z.state
order by l5.location;