SQL: Output all names which belong to a category where all the countries within it are the same

前端 未结 3 1138
难免孤独
难免孤独 2021-01-28 06:59

I have the following table called Stores:

Name          |   Country   |   Category 
Pharmacy          Japan         Health
Green Vine        Italy         Dining         


        
相关标签:
3条回答
  • 2021-01-28 07:23

    You can use EXISTS :

    SELECT t.*
    FROM table t
    WHERE EXISTS (SELECT 1 
                  FROM table t1 
                  WHERE t1.Country = t.Country AND 
                        t1.category = t.category AND
                        t1.Name <> t.Name
                 );
    
    0 讨论(0)
  • 2021-01-28 07:31

    You can use following query to get all such categories for which all countries are same:

        Select t.category
        From table t
        Group by t.category
        Having count(distinct country)=1
    

    Then you can use it to get StoreNames:

        Select t.name
        From table t
        Where t.category in
        ( Select t.category
        From table t
        Group by t.category
        Having count(distinct country)=1)
    

    This syntax is compatible to MS sql server, but I hope logic can be translated to mysql.

    0 讨论(0)
  • 2021-01-28 07:35

    You can use aggregation with a HAVING clause, that checks that the minimum country is the same as the maximum country for a category, i.e. all countries are the same (if there cannot be NULLs, which seems to be the case). Then inner join these categories.

    SELECT *
           FROM elbat t1
                INNER JOIN (SELECT t2.category
                                   FROM elbat t2
                                   GROUP BY t2.category
                                   HAVING max(t2.country) = min(t2.country)) x
                           ON x.category = t1.category;
    
    0 讨论(0)
提交回复
热议问题