2016-02-09 56 views
-1

我有以下查詢:SQL查詢使用PostgreSQL

SELECT DISTINCT "stylists".* FROM "stylists" 
INNER JOIN "category_stylists" ON "category_stylists"."stylist_id" = "stylists"."id" 
WHERE category_stylists.category_id IN (1,2) 

但我想按類別訂購的造型師。

例如:

Stylists 
id | Name 
1  Sebastian 
2  Jhon 

Categories 
id | Name 
1  Wedding 
2  Office 

Stylist_Categories 
id | stylist_id | category_id 
1   1    1 
2   2    1 
3   2    2 

所以,如果我申請我的查詢,我得到了兩個師,但我需要經常爲了通過多少種類有造型師。我的意思是在這個例子中JHON將是第一排,因爲有CATEGORY_ID 1和2 CATEGORY_ID

結果預計:

Stylists 
id | Name 
2  Jhon 
1  Sebastian 

提前感謝!

回答

1

嘗試通過它計算每個設計師和訂單類別:

SELECT "id","name" from(
    SELECT "stylists"."id", "stylists"."Name",count(stylists.id) as cnt FROM "stylists" 
    INNER JOIN "category_stylists" ON "category_stylists"."stylist_id" = "stylists"."id" 
    WHERE category_stylists.category_id IN (1,2) 
    group by "stylists"."id", "stylists"."Name") 
order by cnt desc 
+0

謝謝!有效!! :D – sebaMelgar

+0

沒問題@sebaMelgar。 – sagi