sql

sqlzoo - SUM and COUNT

yjs3819 2021. 7. 23. 20:13
728x90

SQL

  1. SELECT SUM(population)
    FROM world
select distinct continent from world;

distinct를 이용해서 중복을 없애던가 혹은

select continent from world group by continent;

group by로 continent로 그룹화를 하던가! 하면 된다.

  1. select sum(gdp) from world where continent = 'Africa';
  2. select count(name) from world where area >= 1000000;

    count집계함수로 쉽게 구할수있다.

  3. select sum(population) from world where name in ('Estonia', 'Latvia', 'Lithuania');

    sum을 사용하지 말고 쿼리를 날려보고 sum을 이용해보면 더 직관적일것이다!

6.
대륙과 대륙의 나라의 개수를 조회하라는 문제이다.
조금 감이안온다.. 어떻게 해야할까?
먼저 continent로 그룹핑 하면 어떻게 되는지 확인하자.

select continent from world group by continent;

continent가 같은 녀석끼리 그룹핑이 되어 조회된걸 확인할수있다.
그럼 여기서 count집계함수를 이용하면 그룹핑된 레코드의 개수를 알수있다.

select continent, count(name) from world group by continent;

7.
6번문제 변형으로 대륙의 나라의 개수를 조회하는데 조건이 하나추가 되었다. 나라의 인구가 적어도 10 million이어야한다.
(10 million = 10,000,000)

select continent, count(name) from world where population >= 10000000 group by continent;

sql은 from -> where -> group by -> having -> select -> order by로 쿼리가 실행된다. 그렇기에 이 쿼리는 where에서 먼저 population >= 10000000로 걸러진 테이블에서 group by될것이다.

8.
HAVING절을 이용해야한다. HAVING절은 GROUP BY다음에 실행되는 조건절로 집계함수를 사용할수있다. where에는 집계함수를 사용할수 없다. sql의 쿼리순서를 생각하면 쉽게 이유를 알수 있다.

select continent from world group by continent having sum(population) >= 100000000;

quiz

  1. 3
  2. 1
  3. 4
  4. 5 (where에서 집계함수 사용못한다.)
  5. 2
  6. 5
  7. 4
  8. 4
728x90

'sql' 카테고리의 다른 글

sqlzoo - SELECT in SELECT  (0) 2021.07.17
sqlzoo - SELECT from nobel  (0) 2021.07.16
sqlzoo - SELECT from World  (0) 2021.07.15
sqlzoo - SELECT basics  (0) 2021.07.14