본문 바로가기
🛠️Skill/SQL

[SQL문법] UNION, UNION ALL / 친구가 가장 많은 사람 구하기 - 602. Friend Requests II

by Istj_eff 2023. 1. 17.

SELECT문 결과를 합치기위해 UNION, UNION ALL을 사용하면 된다.

차이점

UNION 사용시 중복을 제거하고, 합쳐져서 출력됨
UNION ALL 사용시 중복까지 모두 포함해서 출력됨

 

조건

1️⃣ 각 쿼리의 컬럼 수 데이터 타입이 일치해야 한다.

2️⃣ 첫 번재 쿼리의 별칭(AS)으로 결과가 출력된다. 두번째 쿼리는 별칭을 생략할 수 있고, 별칭을 지정해도 첫번째 쿼리의 별칭으로 결과가 출력된다.

3️⃣ ORDER BY는 쿼리 마지막에 사용하고, 합쳐진 모든 결과를 정렬한다. 별칭 및 컬럼 순번으로 정렬 가능 (A.col 불가능)

 

SELECT 'park' AS last_name -- 첫번째 쿼리의 별칭으로 출력됨
	, salary AS sal
FROM emp
GROUP BY dep

UNION ALL -- 중복 포함

SELECT 'lee' AS last_name
	, salary AS col_sal -- 컬럼지정해도 'sal'로 출력됨
FROM emp
GROUP BY dep

ORDER BY sal DESC; -- ORDER BY는 마지막에

 


예제 - 리트코드 문제

602. Friend Requests II: Who Has the Most Friends 

 

https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/

 

Friend Requests II: Who Has the Most Friends - LeetCode

Can you solve this real interview question? Friend Requests II: Who Has the Most Friends - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

Write an SQL query to find the people who have the most friends and the most friends number.

친구가 가장 많은 사람과 친구 번호가 가장 많은 사람을 찾는 SQL 쿼리를 작성하세요.

 

EXAMPLE

Input: 
RequestAccepted table:
+--------------+-------------+-------------+
| requester_id | accepter_id | accept_date |
+--------------+-------------+-------------+
| 1            | 2           | 2016/06/03  |
| 1            | 3           | 2016/06/08  |
| 2            | 3           | 2016/06/08  |
| 3            | 4           | 2016/06/09  |
+--------------+-------------+-------------+

Output: 
+----+-----+
| id | num |
+----+-----+
| 3  | 3   |
+----+-----+

 

CODE

SELECT DISTINCT id, COUNT(*) num 
FROM ((select requester_id AS id, accepter_id AS friend
       from RequestAccepted) 
     UNION ALL
      (select accepter_id AS id, accepter_id AS friend 
       from RequestAccepted)) Tab
GROUP BY id
ORDER BY num DESC
LIMIT 1

 

 

댓글