我有下表。如何查询 Table Team 如下:
ID,Name,City,League
1,Name1,City1, A
2,Name2,City1, B
诀窍是获取每个城市的数据,并将该数字与整个表格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)
所有不存在联赛且不在与该城市关联的联赛列表中的城市:
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))
几乎和你用英语说的一样,但有一点不同......你想要所有城市在所有联赛中都有一个名字,或者换种说法,你想要所有不存在联赛的城市在所有联赛中都没有名字它来自那个城市。;...
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) ))