如何在以下情况下编写查询?

时间:2012-10-09 02:10:40

标签: sql

我有下表。我该如何查询 表团队如下:

    ID,Name,City,League
    1,Name1,City1, A
    2,Name2,City1, B

3 个答案:

答案 0 :(得分:2)

诀窍是获得每个城市COUNT(DISTINCT League),并将该数字与整个表格中的联盟COUNT(DISTINCT League)总数进行比较。

SELECT
  City,
  COUNT(DISTINCT League) AS numleagues
FROM yourtable
GROUP BY City
/* Only cities which have the same number of distinct leagues as the total number of distinct leagues */
HAVING COUNT(DISTINCT League) = (SELECT COUNT(DISTINCT League) FROM yourtable)

Here it is in action in SQLFiddle

答案 1 :(得分:0)

所有没有联盟的城市不在与该城市相关联的联赛列表中:

 SELECT DISTINCT City FROM Teams T1 WHERE NOT EXISTS
    (SELECT * FROM Teams T2 WHERE League NOT IN 
      (SELECT League FROM Teams T3 WHERE T3.City = T1.City))

答案 2 :(得分:0)

几乎就像你用英语说的那样,但有一点......你想要所有联盟中都有名字的所有城市,或者改写,你想要所有没有联盟但没有联盟的城市来自那个城市的名字。; ..

  Select Distinct City From Table t
  Where Not Exists
    (Select Distinct League From Table L
     Where Not Exists 
         (Select * From Table
          Where City = t.City
             And League = L.League 
             And Name Not in 
                  (Select distinct Name from table 
                   Where City = t.City) ))