SQL Sub_query and joint

Question:

Use a sub-query to determine the Community Area Name with most number of crimes?

i have been trying to solve this Question for few days and I’m having a complete block

would any of you please help me!!

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);
Asked By: Abdelrhman Dameen

||

Answers:

I am assuming you want something like this:

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;

I have no idea how the number of crimes is determined, so I made up a column.

Note that if there are ties, this returns an arbitrary area.

Answered By: Gordon Linoff

I believe you can try something like this:

%%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) ;
Answered By: guestfortoday
    %%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)
Answered By: maximus

Try this:

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

I used top 2 cause de first one with most crimes have no community_area_number

Answered By: Cristiane Izumi
result = %sql SELECT COMMUNITY_AREA_NUMBER, 
    COUNT(*) AS COUNTING_CRIMES FROM CRIME_DATA 
    GROUP BY COMMUNITY_AREA_NUMBER ORDER BY COUNTING_CRIMES DESC LIMIT 1
result = result[0][0]

comunity_area_name = %sql SELECT COMMUNITY_AREA_NAME 
    FROM CENSUS_DATA WHERE COMMUNITY_AREA_NUMBER =:result
comunity_area_name
OUTPUT: Austin

Hello guys, I also had the same question (Hands-on Lab: Problem 10), you could try this code. It worked for me

Answered By: dorstan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.