On the journey of

[LEETCODE] SQL50 : 595.Big Countries,1148.Article Views 1 본문

코딩테스트/SQL

[LEETCODE] SQL50 : 595.Big Countries,1148.Article Views 1

dlrpskdi 2023. 8. 12. 20:50

프로그래머스에 이어 다시! 리트코드 재개한다 ...... ! 아좌 (...)


1. Big Countries : https://leetcode.com/problems/big-countries/?envType=study-plan-v2&envId=top-sql-50 

 

Big Countries - LeetCode

Can you solve this real interview question? Big Countries - Table: World +-------------+---------+ | Column Name | Type | +-------------+---------+ | name | varchar | | continent | varchar | | area | int | | population | int | | gdp | bigint | +-----------

leetcode.com

A country is big if:

  • it has an area of at least three million (i.e., 3000000 km2), or
  • it has a population of at least twenty-five million (i.e., 25000000).

Write a solution to find the name, population, and area of the big countries.

Return the result table in any order.

The result format is in the following example.

 

  • 오라클 환경이었는지조차 기억이 안 나서 오라클로 설정하고 진행. 
  • big으로 판단하는 기준이 2가지이다. 둘 중 하나만 충족하면 되므로 or 활용해서 조건문 작성(부등식)
  • 예시처럼, big으로 판단된 나라의 name과 population, area 칼럼을 select해서 return하면 됨 : select name, population, area
  • 기본 테이블명 world니까 from world
  •  
select name, population, area 
from world 
where area >= 3000000 or population >= 25000000;

결과 : Yay!!


2. 1148 Article Views I : https://leetcode.com/problems/article-views-i/?envType=study-plan-v2&envId=top-sql-50 

 

Article Views I - LeetCode

Can you solve this real interview question? Article Views I - Table: Views +---------------+---------+ | Column Name | Type | +---------------+---------+ | article_id | int | | author_id | int | | viewer_id | int | | view_date | date | +---------------+---

leetcode.com

Write a solution to find all the authors that viewed at least one of their own articles.

Return the result table sorted by id in ascending order.

The result format is in the following example.

  • 먼저 example처럼 output엔 id만 있어야 한다. 이 id는 author_id가 rename한 거니까, 'as' 구문을 추가해야 한다
  • 테이블명 views: from Views
  • 조건이 크게 3가지다. 먼저 author_id = viewer_id 여야 하니 where구문에 해당 사항 추가
    • group by, order by 조건이 하나씩 있다. 같은 id끼리 모으라 했으니까 둘 다 뒤에 author_id를 넣어주면 됨
    • 주의사항: as 'id'를 넣는다고 해도, 실행 전까지 컴퓨터는 'author_id'로 인식하고 있다. 때문에 id가 아닌 author_id로 group/order by 진행해야 함
    • 종합해보면
SELECT author_id as 'id'
FROM Views
WHERE author_id = viewer_id
GROUP BY author_id
ORDER BY author_id

<Run결과>

<Submit 결과> 

왜 이번엔 따로따로 적었냐고..? 그냥.... ㅎ