Step by Step

코딩 테스트 대비 개념정리 - SQL 본문

Algorithms

코딩 테스트 대비 개념정리 - SQL

짤진이 2024. 5. 10. 23:33
반응형
select round(avg(daily_fee)) as average_fee from car_rental_company_car
where car_type in ("SUV")

 

✏️.  개념

round(123.243, 1) => 123.2 , 소수 둘째자리에서 반올림

round(123.243, 2) => 123.24 , 소수 셋째자리에서 반올림

round(123.24, -1) => 120 , 정수 첫째자리에서 반올림

 

SQL WHERE절에서는 집계함수를 쓸 수 없다.

SUM, AVG, COUNT를 사용하려면 서브쿼리를 짜야한다.


 

select book_id, date_format(published_date,"%Y-%m-%d") as published_date from book
where category = "인문" and year(published_date) = 2021

 

✏️.  개념

date_format(date , "%Y-%m-%d") => 2024-03-12

year(날짜) => 2024

month(날짜) => 09


 

select flavor from first_half
order by total_order desc, shipment_id

 

✏️.  개념

desc는 내림차순, asc는 오름차순

내림차순, 오름차순은 순서대로 작성해야한다.


 

select concat(max(length),'cm') as max_length from fish_info

 

✏️.  개념

concat 함수를 사용하면 단위 등을 붙일 수 있다.

concat(str1, '  ', sstr2)

concat(str1, 'cm')


SELECT mcdp_cd as 진료과코드, count(mcdp_cd) as 5월예약건수 from appointment
where apnt_ymd like ('2022-05%')
group by mcdp_cd
order by 5월예약건수, 진료과코드

✏️.  개념

~~로 끝나는 것 like '%것'

~~로 시작하는 것 like '2022-05%'

 


select round(avg(ifnull(length,10)),2) as AVERAGE_LENGTH from fish_info

✏️.  개념

ifnull(value, "N")

value가 null일 때 2번째 인자값으로 대체


select order_id, product_id, date_format(out_date,"%Y-%m-%d") as out_date,
case
    when out_date <= "2022-05-01" then "출고완료"
    when out_date > "2022-05-01" then "출고대기"
    else '출고미정'
end "출고여부"
from food_order
order by order_id

✏️.  개념

Case When 절


SELECT DATEADD(YEAR, -1, '2021-07-12') AS [1년전] 
     , DATEADD(YEAR, 1, '2021-07-12')  AS [1년후]

✏️.  개념

Year, Month, Day, Hour, Minute, Second만 변경하여 사용이 가능하다.


select car_id, round(avg(datediff(end_date, start_date)+1),1) as average_duration
from car_rental_company_rental_history
group by car_id
having avg(datediff(end_date, start_date)+1) >= 7

order by average_duration desc, car_id desc

✏️.  개념

datediff(end_date, start_date)

반응형