2017-06-07 79 views
1

我是新來的SQL和我使用postgres 9.6,我有2個查詢,我想加入他們到1。我想通過這個字段上按我在這裏SQL如何使用不同的加入計數函數內

1查詢

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 

第一查詢結果

enter image description here

第二查詢結果:魯茲應該是在頂部不底部 enter image description here

回答

1

可以使用熱膨脹係數或子查詢:

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; 
+0

感謝那些工作 –