2009-09-09 75 views
14

我有兩個表:如何使用postgresql進行排序?

Companies: (id, name, city) 
Workers: (id, name) 

我想獲得的所有公司和聘用過的員工數量進行排序。

結果應該給:

count | company id | company name | city 
------------------------------------------ 
90   6   foo corp  NY 
45   9   bar corp  LA 
0   3   foobar corp  HO 

我想:

select 
    c.*, 
    count(w.id) as c 
from 
    companies c 
left join 
    workers w 
on 
    c.id = w.company_id 
group by 
    c.id 
order by 
    c desc; 

但是這不是工作,因爲它告訴我組由g.name太:/

任何想法?

回答

19

你別名表和列一樣的東西,所以不要做。這不是無效的,只是很難遵循。

不管怎麼說,包括您要選擇不在你group by聚集所有列:

select 
    count(w.id) as mycount, 
    w.company_id, 
    c.company_name, 
    c.city 
from 
    companies c 
    left join workers w on 
     c.id=w.company_id 
group by 
    w.company_id, 
    c.company_name, 
    c.city 
order by mycount desc; 
+0

我的表實際上是要高於兩列(城市名)時,我應該GROUP BY ALL他們? – Ggolo 2009-09-09 23:53:37

+0

我認爲你應該爲GROUP BY子句起作用,否則查詢將會失敗 – MaxiWheat 2009-09-10 00:19:39

+1

@Ggolo:你選擇的任何列,你必須'group by'。 – Eric 2009-09-10 00:28:29

0

試試這個作爲一個子查詢:

SELECT C.* 
FROM 
(
    SELECT C.Id, C.Company_Name, C.City, COUNT(W.Id) AS CNT 
    FROM Companies C 
    LEFT JOIN Workers W ON W.Company_Id = C.Id 
    GROUP BY C.Id, C.Company_Name, C.City 
) T 
ORDER BY T.CNT 
相關問題