2012-10-09 151 views
1

我有下表。如何查詢 表團隊如下:如何在以下情況下編寫查詢?

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

您想要的結果是什麼樣子? –

+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

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)) 
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)))