我对SQL很新,但是在互联网上搜索了这个答案,我仍然无法获取我的COUNT和EXCEPT语句来选择我想要的内容。
我的数据库:
sqlite> CREATE TABLE Football(Team TEXT, Player TEXT, Age INTEGER, primary key(Team, Player));
sqlite> .separator ,
sqlite> .import databaseTest Football
sqlite> .headers on
sqlite> .mode col
sqlite> SELECT Team, Player, Age FROM Football ORDER BY Team;
Team Player Age
---------- ---------- ----------
Arsenal Cech 38
Arsenal Giroud 29
Arsenal Sanchez 28
Arsenal Walcott 27
Chelsea Costa 29
Chelsea Courtois 25
Chelsea Hazard 26
Chelsea Willian 26
Liverpool Can 23
Liverpool Coutinho 24
Liverpool Wjinaldum 25
Liverpool Woodburn 17
Manchester Aguero 29
Manchester Jesus 19
Manchester Silva 28
Manchester Toure 34
Manchester De Gea 26
Manchester Felliani 29
Manchester Rooney 32
Manchester Schweinste 35
Tottenham Delle Ali 22
Tottenham Kane 24
Tottenham Rose 24
Tottenham Vertonghen 27
我想要做的是SELECT
没有30岁以上球员的COUNT
球队。所以选择声明应该是3(切尔西,利物浦,托特纳姆)。
这是我已经尝试并假设可行的陈述:
sqlite> SELECT COUNT(DISTINCT Team) FROM Football
...> EXCEPT
...> SELECT COUNT(DISTINCT Team) FROM Football WHERE Age > 30;
COUNT(DISTINCT Team)
--------------------
6
但是你可以看到它返回'6'。我做错了什么,我怎样才能得到正确的结果?
答案 0 :(得分:1)
这是另一种方式。查看每个团队的最长年龄:
SELECT COUNT(*)
FROM (SELECT Team
FROM Football
GROUP BY Team
HAVING MAX(Age) <= 30
) t;
您也可以使用EXCEPT
,但这也需要子查询。您需要在执行计数之前执行设置操作:
SELECT COUNT(DISTINCT TEAM)
FROM (SELECT Team FROM Football
EXCEPT
SELECT Team FROM Football WHERE Age > 30
) t;
严格来说,此查询可以使用COUNT(*)
而不是COUNT(DISTINCT)
。但是,记住EXCEPT
(如UNION
)删除重复值可能很麻烦。