[241002] SQL 기초 강의

JunichiK·2024년 10월 2일

SQL 스터디

목록 보기
10/21

코드 카타

문제 & 제출 답안

오답노트

  • Date_format(날짜 컬럼, ‘%Y-%m-%d’) : 날짜 형식을 바꿔주는 함수
    SELECT 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-날짜-형식-변경
    • 사용 방법 : 변환하려는 날짜와 구분자(-, . 등)를 넣어서 사용
      • %Y : 연도 전체 출력
      • %y : 연도 끝 2자리만 출력
      • %M : 영문 월 출력
      • %m : 숫자 월 출력
      • %d : 숫자 일 출력 (한자리 수 앞에 0 포함)
      • %e : 숫자 일 출력 (한자리 수는 앞에 0 미포함)
  • hour(날짜 컬럼)
    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/60
    • 사용방법 : hour(날짜)
    • 시간 출력됨.
  • 두 개 이상 like
    SELECT 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/16
  • 일자별 카테고리의 판매량에서 매출 구하기
    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 asc
    https://ror-coding.tistory.com/7
    • group by 이후 sum, avg 같은 함수 미사용 시, 가장 위에 값이 출력됨!!
  • Datediff(뒤에 날짜, 앞에 날짜)
    select 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
    • 사용 방법 : Datediff(뒤에 날짜, 앞에 날짜)
      • 뒤에 날짜값 - 앞에 날짜값
    • 추가 문법 : Timestampdiff(단위, 날짜1, 날짜2)
      • 날짜 1 - 날짜 2 값을 단위로 변환

강의 스터디

수강할 강의

스터디를 진행할 강의를 링크해주세요.

[SQL] 예제로 익히는 SQL - 2회차

강의에서 필수 사용되는 문법 요약

강의에서 필수로 사용되는 문법에 대한 개념을 요약해주세요.

  1. 세미콜론(;) 의 쓰임새 : 구문과 구문 사이를 구분 지어줌.

    select * from table;
    // 세미콜론 사용 덕분에 위에서 Ctrl + Enter 누르면 위에것만 실행됨.
    
    select id from table;
  2. distinct : 중복값 제거

    select name from table; // 1번
    
    select distinct name from table; //2번
    
    /* 1번 : 중복돼도 이름 다 가져옴.
    	 2번 : 중복없이 고유 이름만 가져옴 */
  3. where : 조건문

    select *
    from table
    where name = '배준호';
    
    /*  1. table 에서
    		2. name이 배준호인
    		3. 모든 필드를 가져와줘 */
  1. case when : 조건에 따라 데이터 구분

    select case when score >= 90 then 'A'
    						when score between 80 and 90 then 'B'
    						else 'C' end as "학점"
    from table;
    • 수행 순서
  1. 다양한 연산자

    • 날짜 데이터가 비어있지 않고
    • 성별이 남자가 아니고
    • 직업이 아나운서 또는 승무원 또는 화가이고
    • 나이가 30세에서 40세 사이
    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/
  • 💪 환경 구축하기

    1. DBeaver 내에서 basic DB 를 새로 만들고, users 테이블을 업로드 하겠습니다.

    2. Database 을 우클릭 하여 Create New Database 를 클릭합니다.

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

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

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

    6. SQL 편집기를 새로 만들어주세요.

  • 과제 1

    • 로그정의서

      로그는 행위에 대한 기록입니다.
      예를들어, logid=100 은 서비스입장 입니다.
      해당 컬럼은 이번 과제에서 사용되지 않습니다.

      구분상세schema
      logid로그idint
      ip_addrip주소string
      first_login_date첫 접속일자, yyyy-mm-ddstring
      game_account_id게임계정idstring
      game_actor_id게임캐릭터idint
      level현재레벨int
      exp현재경험치int
      serverno서버넘버int
      zone_id지역넘버int
      etc_num1파티idint
      etc_num2파티원수int
      etc_str1아이템 획득경로string
      etc_num3아이템 획득량int
      etc_str2아이템 이름string
  • 문제1 조건절 where 구문의 활용

    조건 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 ;
profile
represent ojeong-dong

0개의 댓글