본문 바로가기
SQL/LeetCode

LeetCode_7. Advanced String Functions / Regex / Clause

by JeoK 2025. 3. 31.

https://leetcode.com/studyplan/top-sql-50/

1667. Fix Names in a Table

문제 : 이름의 첫 번째 문자만 대문자, 나머진 소문자로 변환

Users table

Concat() : 문자열 합치기

Left + Substring 

select user_id,
    concat(
      upper(left(name, 1)), -- 대문자(첫 글자)
      lower(substring(name, 2)) -- 소문자(두 번째 글자부터 끝까지 추출)
    ) as name
from users
order by 1
;

1527. Patients With a Condition

문제 : 제 1형 당뇨병 환자의 정보 추출 (: DIAB1 접두사로 시작)

Patients table

regexp_like : 글자 위치, 시작/ 끝, 주변 문자 조건까지 정밀하게 체크 > ^ (시작) , $ (끝) , | (또는)

select patient_id, patient_name, conditions
from patients
--처음부터 DIAB1인 경우 or 문자열 중간에 공백 + DIAB1이 나오는 경우
where regexp_like (conditions, '^DIAB1| DIAB1')
;

like :  글자 포함 여부 > % (모든 문자열) , _ (한 글자)

select *
from patients
where conditions like 'DIAB1%' --DIAB1로 시작하는 경우
    or conditions like '% DIAB1% --중간에 공백 + DIAB1이 있는 경우
;

196. Delete Duplicate Emails

문제 : 중복 이메일은 하나만 남기되, id 값이 가장 작은 것만 보존하는 쿼리

Person table

- self join하여 중복 이메일 찾기

delete p1
from person p1
inner join person p2 
on p1.email = p2.email and p1.id > p2.id --조건 2개 (이메일이 같은 경우, p1의 id가 더 클 때만 선택)
;

176. Second Highest Salary

문제 : 두 번째로 높은 급여 찾기 (값이 없다면 null 반환)

Employee table

1. 전체 급여 중 가장 큰 값 찾기

2. 그보다 작은 급여 중 가장 큰 값 찾기

select max(salary) as SecondHighestSalary --가장 큰 값
from employee
where salary < (select max(salary) --두번째로 큰 값
		from employee) 
;

1484. Group Sold Products By The Date

문제 : 각 날짜마다 판매된 제품의 수와 이름 찾기

Activities table

1. count(distinct product) as num_sold : 그 날짜에 팔린 서로 다른 제품의 수 

2. group_concat(distinct product order by product separator ',') as products

: 같은 날짜에 팔린 서로 다른 제품명을 ','로 구분하여 문자열로 연결

select sell_date,
    count(distinct product) as num_sold,
    group_concat(distinct product order by product separator ',') as products
from activities
group by sell_date 
;

1327. List the Products Ordered in a Period

문제 : 2020년 2월에 최소 100개 이상 주문된 제품의 수량 확인

Products table
Orders table

select p.product_name, sum(o.unit) as unit
from products as p 
inner join orders as o on p.product_id = o.product_id 
where o.order_date like '2020-02%'
group by 1
having sum(o.unit) >= 100
;

1517. Find Users With Valid E-Mails

문제 : 유효한 이메일을 가진 유저 찾기 (접두사: 대소문자, 숫자, '_', '.', '-' / 도메인 : @leetcode.com )

Users table

regexp == rlike

1. ^ : 문자열 시작

2. [a-zA-Z] : 반드시 첫 글자가 영문자

3. [a-zA-Z0-9_.-]*+ : *, +의 앞에 있는 것을 0번 이상 반복(*) 1번이상 반복(+) ... (영어/숫자/밑줄/마침표/하이픈)

4. @leetcode\\.com : 정확히 @leetcode.com으로 끝나야 한다

5. $ : 문자열 끝

 

select user_id, name, mail 
from Users 
where mail rlike '^[a-zA-Z][a-zA-Z0-9_.-]*+@leetcode\\.com$'
;

'SQL > LeetCode' 카테고리의 다른 글

LeetCode_6. SubQueries  (0) 2025.03.31
LeetCode_5. Advanced Select and Joins  (0) 2025.03.31
LeetCode_4. Sorting and Grouping  (0) 2025.03.31
LeetCode_3. Basic Aggregate Functions  (0) 2025.03.31
LeetCode_2. Basic Joins  (0) 2025.03.31