SELECT animal_id, name, date_format(animal_ins.datetime, '%Y-%m-%d') as '날짜'
from animal_ins
order by animal_id ascSELECT dr_name, dr_id, mcdp_cd, date_format(doctor.hire_ymd, '%Y-%m-%d')
from doctor
where mcdp_cd in ('CS', 'GS')
order by hire_ymd desc, dr_name ascSELECT *
from food_product
order by price desc limit 1SELECT animal_id
from animal_ins
where name is null
order by animal_id ascSELECT count(*)
from user_info
where (age between 20 and 29) and (joined like '2021%')SELECT animal_id, name,
case when sex_upon_intake like '%Neutered%' then "O"
when sex_upon_intake like '%Spayed%' then "O"
else "X" end as '중성화'
from animal_ins
order by animal_id ascselect code, count(*)
from
(SELECT *, substring(product_code, 1, 2) as code
from product) A
group by codeSELECT animal_type, count(*)
from animal_ins
group by animal_type
order by animal_type ascSELECT hour(datetime), count(*)
from animal_outs
where hour(datetime) between 9 and 19
group by 1
order by 1 ascSELECT MCDP_CD as '진료과 코드', count(*) as '5월예약건수'
from appointment
where APNT_YMD like '2022-05%'
group by 1
order by 2 asc, 1 ascSELECT PT_NAME, PT_NO, GEND_CD, AGE, ifnull(TLNO, "NONE")
from patient
where age <= 12 and gend_cd = 'w'
order by 4 desc, 1 ascSELECT flavor
from first_half
order by total_order desc, shipment_id ascSELECT car_type, count(*) as 'CARS'
from car_rental_company_Car
where
(OPTIONS like '%통풍시트%') or
(OPTIONS like '%열선시트%') or
(OPTIONS like '%가죽시트%')
group by 1
order by 1 ascSELECT i.name, i.datetime
from animal_ins i
left join animal_outs o on o.animal_id = i.animal_id
where o.animal_id is null
order by i.datetime asc limit 3SELECT b.category, sum(bs.sales) as total_sales
from book b
inner join book_sales bs on b.book_id = bs.book_id
where bs.sales_date like '2022-01%'
group by 1
order by 1 asc;SELECT p.product_code, (p.price * sum(o.sales_amount)) as rev
from offline_sale o
left join product p on o.product_id = p.product_id
group by 1
order by 2 desc, 1 ascSELECT i.animal_id, i.name
from animal_outs o
inner join animal_ins i on o.animal_id = i.animal_id
where o.datetime < i.datetime
order by i.datetime ascselect animal_id, name
from
(
SELECT i.animal_id, i.name, Datediff(o.datetime, i.datetime) as '보호기간'
from animal_outs o
inner join animal_ins i on o.animal_id = i.animal_id
order by 3 desc limit 2
) aSELECT i.animal_id, i.animal_type, i.name
from animal_outs o
inner join animal_ins i on o.animal_id = i.animal_id
where i.sex_upon_intake like '%Intact%' and
(o.sex_upon_outcome like '%Spayed%' or
o.sex_upon_outcome like '%Neutered%')SELECT b.book_id, a.author_name, date_format(b.published_date, '%Y-%m-%d') as date
from book b
left join author a on b.AUTHOR_ID = a.AUTHOR_ID
where b.category = '경제'
order by b.published_date ascSELECT 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 as '출고여부'
from food_order
order by 1 ascSELECT i.ingredient_type, sum(f.total_order)
from first_half f
inner join icecream_info i on f.flavor = i.flavor
group by 1
order by 2 ascSELECT animal_id, name, sex_upon_intake
from animal_ins
where name in ('Lucy', 'Ella', 'Pickle', 'Rogan', 'Sabrina', 'Mitty')
order by animal_id ascSELECT book_id, date_format(published_date, '%Y-%m-%d')
from book
where published_Date like '2021%' and
category = '인문'
order by 2 ascSELECT round(avg(Daily_fee),0) as average_fee
from car_rental_company_car c
where car_type = 'SUV'select *
from
(
SELECT b.writer_id, u.nickname, sum(b.price) as sum
from used_goods_board b
left join used_goods_user u on b.writer_id = u.user_id
where b.status = 'done'
group by 1
) a
where sum >= 700000
order by sum ascSELECT animal_id, name, date_format(animal_ins.datetime, '%Y-%m-%d') as '날짜'
from animal_ins
order by animal_id asc https://velog.io/@gloz0315/SQL-날짜-형식-변경SELECT hour(datetime), count(*)
from animal_outs
where hour(datetime) between 9 and 19
group by 1
order by 1 asc https://extbrain.tistory.com/60SELECT car_type, count(*) as 'CARS'
from car_rental_company_Car
where
(OPTIONS like '%통풍시트%') or
(OPTIONS like '%열선시트%') or
(OPTIONS like '%가죽시트%')
group by 1
order by 1 asc https://mousepotato.tistory.com/16SELECT p.product_code, (p.price * sum(o.sales_amount)) as rev
from offline_sale o
left join product p on o.product_id = p.product_id
group by 1
order by 2 desc, 1 asc https://ror-coding.tistory.com/7select animal_id, name
from
(
SELECT i.animal_id, i.name, Datediff(o.datetime, i.datetime) as '보호기간'
from animal_outs o
inner join animal_ins i on o.animal_id = i.animal_id
order by 3 desc limit 2
) a https://extbrain.tistory.com/78스터디를 진행할 강의를 링크해주세요.
강의에서 필수로 사용되는 문법에 대한 개념을 요약해주세요.
세미콜론(;) 의 쓰임새 : 구문과 구문 사이를 구분 지어줌.
select * from table;
// 세미콜론 사용 덕분에 위에서 Ctrl + Enter 누르면 위에것만 실행됨.
select id from table;
distinct : 중복값 제거
select name from table; // 1번
select distinct name from table; //2번
/* 1번 : 중복돼도 이름 다 가져옴.
2번 : 중복없이 고유 이름만 가져옴 */
where : 조건문
select *
from table
where name = '배준호';
/* 1. table 에서
2. name이 배준호인
3. 모든 필드를 가져와줘 */
case when : 조건에 따라 데이터 구분
select case when score >= 90 then 'A'
when score between 80 and 90 then 'B'
else 'C' end as "학점"
from table;

다양한 연산자
select *
from table
where DATE IS NOT NULL
AND (GENDER <> 'M')
AND JOB IN ('아나운서', '승무원', '화가')
AND (AGE BETWEEN 30 AND 40)
order by date desc
연산의 우선순위를 명시하기 위해, 각 조건에 괄호()를 작성하여 우선적으로 연산하고,
해당 조건들을 모두 만족해야 하므로, 각 조건들은 AND 연산자로 묶어주어야 해요.
MySQL 연결 방법
https://hongong.hanbit.co.kr/mysql-%EB%8B%A4%EC%9A%B4%EB%A1%9C%EB%93%9C-%EB%B0%8F-%EC%84%A4%EC%B9%98%ED%95%98%EA%B8%B0mysql-community-8-0/
💪 환경 구축하기
DBeaver 내에서 basic DB 를 새로 만들고, users 테이블을 업로드 하겠습니다.
Database 을 우클릭 하여 Create New Database 를 클릭합니다.

Database name 을 basic 으로 지정해 보겠습니다.

basic DB 안에 새로운 테이블 생성을 위해, users.csv 파일을
업로드 해주세요.

한글컬럼 깨짐 방지를 위해, euc-kr 로 인코딩 설정을 변경해주세요.

SQL 편집기를 새로 만들어주세요.
과제 1
로그정의서
로그는 행위에 대한 기록입니다.
예를들어, logid=100 은 서비스입장 입니다.
해당 컬럼은 이번 과제에서 사용되지 않습니다.
| 구분 | 상세 | schema |
|---|---|---|
| logid | 로그id | int |
| ip_addr | ip주소 | string |
| first_login_date | 첫 접속일자, yyyy-mm-dd | string |
| game_account_id | 게임계정id | string |
| game_actor_id | 게임캐릭터id | int |
| level | 현재레벨 | int |
| exp | 현재경험치 | int |
| serverno | 서버넘버 | int |
| zone_id | 지역넘버 | int |
| etc_num1 | 파티id | int |
| etc_num2 | 파티원수 | int |
| etc_str1 | 아이템 획득경로 | string |
| etc_num3 | 아이템 획득량 | int |
| etc_str2 | 아이템 이름 | string |
조건 1) first_login_date 컬럼이 2023-01-01 초과인 날짜의
game_account_id, game_actor_id, serverno 를 추출해주세요.
결과값은 아래와 같은 형태이며, 정렬을 하지 않았으므로 결과값 순서는 달라질 수 있습니다.
아래 그림은 전체 중 일부입니다.

select game_account_id , game_actor_id , serverno
from users u
where first_login_date > '2023-01-01';
과제 2
문제2 - 조건절 where 구문의 응용
조건1) level 컬럼이 10 초과이고
조건2) serverno컬럼이 1이 아니며
조건3) 아이템 이름컬럼이 레벨업 패키지 또는 시즌패스이고
조건4) 아이템 획득 경로가 상점에서 구매한 경우의
first_login_date, ip_addr, exp, zone_id 를 추출하고 결과값을 first_login_date, ip_addr기준 내림차순으로 정렬해주세요. 결과값은 아래와 같은 형태입니다.
아래 그림은 전체 중 일부입니다.

select first_login_date , ip_addr , exp, zone_id
from users u
where level > 10 and
serverno <> 1 and
etc_str2 in ('레벨업 패키지', '시즌패스') and
etc_str1 like '%상점%'
order by first_login_date desc, ip_addr desc;
과제 3
- 문제3 - 조건절 case when 구문의 활용
조건1) case when 구문을 사용하여 레벨구간을 아래와 같이 구분해주시고, as 를 사용하여 컬럼이름을 ‘levelgroup’ 으로 설정해주세요.
[레벨구간]
◦ 1~10Lv 이하
◦ 11~20Lv 이하
◦ 21~30Lv 이하
◦ 31~40Lv 이하
◦ 41~50Lv 이하
◦ 51~60Lv 이하
◦ 61~70Lv 이하
◦ 71~80Lv 이하
◦ 81~90Lv 이하
◦ 91~100Lv**
game_actor_id, level, levelgroup, first_login_date 컬럼을 추출해주시고, first_login_date를 기준으로 내림차순 정렬해주세요. 결과값은 아래와 같아야 합니다.
아래 그림은 전체 중 일부입니다.

select game_actor_id , level,
case when level <= 10 then '1~10Lv 이하'
when level between 11 and 20 then '11~20Lv 이하'
when level between 21 and 30 then '21~30Lv 이하'
when level between 31 and 40 then '31~40Lv 이하'
when level between 41 and 50 then '41~50Lv 이하'
when level between 51 and 60 then '51~60Lv 이하'
when level between 61 and 70 then '61~70Lv 이하'
when level between 71 and 80 then '71~80Lv 이하'
when level between 81 and 90 then '81~90Lv 이하'
else '91~100Lv' end as levelgroup,
first_login_date
from users u
order by first_login_date desc ;