SQL 10

pivot 테이블 만들기

pivot table: 여러 데이터 중 원하는 데이터만 뽑아서 행과 열에 배치하여 만든 테이블구조select 열1, 열2, 열3, 열4from 테이블 또는 서브쿼리문group by 행 10대-50대까지 연령대별로 음식 종류마다 주문한 횟수를 보여주는 피벗 테이블10대-50대까지 연령을 case when문으로 나누고, count함수로 주문 개수를 센 다음위의 것을 서브쿼리문에 넣고 쿼리문에서는 열을 지정해준다SELECT fo.cuisine_type,              case when age between 10 and 19 then 10                       when age between 20 and 29 then 20                      when age betwe..

SQL 2024.09.02

null, coalesce

데이터의 값이 상식적이지 않아서 제외하고 싶거나 다른 값으로 대체하고 싶을 수 있다제외하는 법1. if 문if(rating'not given', rating, null): rating의 값이 not given이 아니면 rating을 그대로 쓰고, not given이면 제외해(=null) 이 문법을 쓰지 않으면 not given은 모두 0으로 간주해서 계산된다.즉 {not given, 1, 2, 5, not given, 6} 이라는 데이터가 있을 때 이들의 평균을 계산하면 (0+1+2+5+0+6)/6 으로 계산된다하지만  null로 처리한 후 계산하면 (1+2+5+6)/4 로 계산된다.  2. where 절의 nullselect *from customerswhere age is not null: age가 ..

SQL 2024.09.01

join

필요한 데이터가 서로 다른 테이블에 있을 때 공통컬럼을 바탕으로 두 테이블을 합하고, 거기서 필요한 정보를 가져오거나 연산할 수 있음 join문의 기본 select a.컬럼1, b.컬럼2from table1 a left/inner join table2 b on a.공통컬럼=b.공통컬럼 table1 a, table2 b에서 a와 b는 두 테이블의 별명left join: 하나의 테이블에만 있는 값이라도 모두 조회inner join: 두 테이블에서 공통된 값만 조회 예시select fo.price, c.agefrom food_orders fo left join customers c on fo.customer_id=c.customer_id:food_orders와 customers 테이블을 합치고 그 중 pric..

SQL 2024.08.31

subquery

이전에 했던 연산결과를 다시 이용하거나, 여러 번의 연산을 수행해야 할 때 유용함기본 구조(select  columnfrom table) a a는 subquery의 별명인데 다른문자나 단어로 써도 상관없다이  subquery문은select columnfrom (select  columnfrom table) a 이렇게 from 다음에 써주면 된다식당별로 주중에는 평균 음식준비 시간 또는 평균 배달시간 중 하나라도 26분 초과이면 지연, 주말에는 둘 중 하나라도 29분 초과이면 지연으로 표기하려면?-> subquery에서 평균 음식준비 시간과 평균 배달시간을 구하고, 그것을 이용해서 case when문으로 조건을 주면 됨평균시간 구하는 subquery문SELECT restaurant_name,        ..

SQL 2024.08.30

if, case

if조건문의 기본if(조건, 조건을 충족할 때, 조건을 충족하지 못할 때)if(age>60, junior, senior) : 나이 60까지는 junior, 60세 넘으면 seniorif 안이나 밖에 각종 포맷(replace, substr, concat), like, in, between 등 사용 가능 select concat('[', if(rating='not given', '0', rating), ']', restaurant_name) "별점",            rating,          restaurant_namefrom food_orders: [별점]식당이름으로 컬럼을 합쳐서 보여주는데 별점에는 만약에 rating=not given이면 0점 그 외에는 받은 rating을 넣어줘 case조건을..

SQL 2024.08.29

replace, substring, concat

replace: 특정 문자를 다른 문자로 바꾸기replace(바꿀 컬럼, 현재값, 바꿀값) select addr          replace(addr, '서울', 'seoul')from addresswhere addr like '%서울%': address 테이블에서 addr컬럼에서 서울이 들어가는 것들을 seoul로 싹 다 바꿔줘ex)서울특별시 서초구 -> seoul특별시 서초구 substring: 특정 문자만 골라서 보기substr(컬럼, 시작위치, 글자수)시작위치와 글자수에는 공백이 포함된다ex 서울특별시 서초구 에서 '서초구'만 뽑으려면 7번째 글자에서 시작하여 3글자를 뽑으면 됨->substr(addr, 7,3) select addr           substr(addr, 1, 2)from f..

SQL 2024.08.28

group by, order by

SQL문의 구조select  컬럼from  테이블where  조건group by 컬럼order by  컬럼 group by: 카테고리별로  select restaurant_name, max(price)from food ordersgroup by restaurant_name:각 레스토랑마다 가장 비싼 음식가격을 보여줘 select cuisine_type, sum(price)from food ordersgroup by cuisine_type: 음식 종류별로 주문금액 합계를 알려줘 order by: 순서대로 select restaurant_name, max(price)from food ordersgroup by restaurant_nameorder by max(price):각 레스토랑마다 가장 비싼 음식가격을..

SQL 2024.08.28

기본 연산, 최대/최소, 개수 구하기

select 다음에 써주면 된다기본 연산select a, b, a+b as c -> c컬럼이 새로 만들어지고 a+b를 한 값이 써진다 select food_preparation_time,        delivery_time,        food_preparation_time + delivery_time as total_time from food_orders select sum(컬럼): 컬럼의 총 합select avg(컬럼): 컬럼의 평균 최대/최소select min(컬럼)  지정한 컬럼의 최솟값select max(컬럼)  지정한 컬럼의 최댓값 select min(price) min_price,        max(price) max_price from food_orders 개수 구하기count: 데이..

SQL 2024.08.27

where 절의 비교연산, between, in, like, 논리연산

비교연산= 같다 같지않다> 크다>= 크거나 같다 select *from customerswhere age >=21:customers 테이블에서 나이가 21세 이상인 데이터를 조회 Betweenbetween A and B : A와 B 사이select *from customerswhere age between 24 and 27:customers 테이블에서 나이가 24-27세 사이인 데이터를 조회 Inin ( ) : ( )안의 조건에 해당하는 것들select *from customerswhere age in (21, 24):customers 테이블에서 나이가 21세와 25세인 데이터를 조회 select *from customerswhere name in ('김도윤', '박채아'):customers 테이블에서 ..

SQL 2024.08.27

select, from

select : 데이터 가져오기from : 어느 테이블에서 가져올지ex)select *from food_orders:food_orders 테이블의 모든 컬럼을 가져오다select pricefrom food_orders:food_orders 테이블의 price 컬럼(가격정보)을 가져오다 컬럼 이름 변경컬럼 as 별명 또는 컬럼 별명별명이 특수문자나 한글일 때는 큰따옴표 사용select price as pfrom food_orders select price pfrom food_orders:food_orders 테이블의 price 컬럼의 이름을 p로 바꾼다 select price as "가격"from food_orders select price "가격"from food_orders:food_orders 테이블..

SQL 2024.08.27