SQL Sub_query 和联合
Posted
技术标签:
【中文标题】SQL Sub_query 和联合【英文标题】:SQL Sub_query and joint 【发布时间】:2021-03-23 09:05:26 【问题描述】:使用子查询来确定犯罪次数最多的社区区域名称?
我这几天一直在尝试解决这个问题,但我遇到了一个完整的问题
请大家帮帮我吧!
select community_area_name, community_area_number
from CHICAGO_PUBLIC_SCHOOLS
where community_area_number in (select community_area_number
from CHICAGO_CRIME_DATA
where community_area_number = '25');
select community_area_number, community_area_name
from CHICAGO_PUBLIC_SCHOOLS
where community_area_number in (select community_area_number
from CHICAGO_CRIME_DATA);
【问题讨论】:
请看:Why should I provide an MCRE for what seems to me to be a very simple SQL query? try exists select community_area_number, community_area_name from CHICAGO_PUBLIC_SCHOOLS a where exists(select '' from CHICAGO_CRIME_DATA b where a.community_area_number =b.community_area_number ) 在一个有类似问题的班级中,如果我们有相同的信息,您的问题不会是您试图从 CHICAGO_PUBLIC_SCHOOLS 表而不是 CENSUS_DATA 表中提取信息吗? 【参考方案1】:我假设你想要这样的东西:
select cps.community_area_number, cps.community_area_name
from CHICAGO_PUBLIC_SCHOOLS cps
where cps.community_area_number = (select ccd.community_area_number
from CHICAGO_CRIME_DATA ccd
order by ccd.num_crimes desc
limit 1
) ccd;
我不知道犯罪数量是如何确定的,所以我做了一个专栏。
请注意,如果存在平局,则返回任意区域。
【讨论】:
【参考方案2】:我相信你可以试试这样的:
%%sql
SELECT COMMUNITY_AREA_NAME, COMMUNITY_AREA_NUMBER AS MOST_CRIMES FROM CENSUS_DATA
WHERE COMMUNITY_AREA_NUMBER IN (SELECT COUNT(COMMUNITY_AREA_NUMBER) FROM CRIME_DATA GROUP BY COMMUNITY_AREA_NUMBER) ;
【讨论】:
【参考方案3】: %%sql select community_area_name
from CENSUS_DATA
where community_area_number = (select A.community_area_number from CHICAGO_CRIME_DATA as A
GROUP BY A.community_area_number
ORDER BY COUNT (A.community_area_number) DESC LIMIT 1)
【讨论】:
【参考方案4】:试试这个:
select COMMUNITY_AREA_NUMBER, COMMUNITY_AREA_NAME FROM ChicagoCensusData WHERE COMMUNITY_AREA_NUMBER IN (SELECT TOP 2 COMMUNITY_AREA_NUMBER FROM ChicagoCrimeData GROUP BY COMMUNITY_AREA_NUMBER ORDER BY COUNT(*) DESC);
我使用了前 2 个原因,第一个原因是大多数犯罪没有 community_area_number
【讨论】:
以上是关于SQL Sub_query 和联合的主要内容,如果未能解决你的问题,请参考以下文章