SQL QUERY使用POSTGRESQL

时间:2016-02-09 15:50:46

标签: 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和category_id 2。

预期结果:

Stylists
id  |  Name
2      Jhon
1      Sebastian

提前致谢!

1 个答案:

答案 0 :(得分: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