Notice
Recent Posts
Recent Comments
Link
«   2026/03   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

ALLYES

[2022년 청년친화형 기업 ESG지원 사업 - 8] 본문

ESG

[2022년 청년친화형 기업 ESG지원 사업 - 8]

Allyes_99 2022. 9. 16. 17:50

일시 : 2022.09.16

시간 : 9:00 ~ 18:00


오전 : DB

오후 : Java


// 문자열 연결

select first_name || last_name
from employees;

 


  • 서브쿼리
    • 쿼리 안에 쿼리가 존재
    • ( )안에 서브쿼리를 기술
    • 임의의 값을 확인하여 조회 할 때
      • 종류
        • 단일 행 서브 쿼리
        • 다중 행 서브 쿼리

문제 : Talyor(176)보다 많이 받는 직원의 이름, 직종 급여를 조회하시오.

select last_name, job_id, salary
from employees
where salary > (select salary from employees where employee_id = 176)

select last_name, job_id, salary
from employees
where salary>8600

단일행 연산자 : = , >, <, >=, <=, <>

 

문제 : 회사직원의 평균급여 보다 급여를 많이 받는 직원의 이름, 직종, 급여를 출력하시오. 

select last_name, job_id, salary
from employees
where salary > ( select avg(salary) from employees);

select table_name
from user_tables;

문제 : 사번이 176인 직원의 직종과 동일한 직종에 근무하는 직원 중에 직원 번호가 150인 직원의 급여보다 많이 받는 직의 이름, 직종, 급여를 조회하시오.

select last_name, job_id, salary
from employees
where job_id = (select job_id from employees where employee_id = 176) 
and salary > ( select salary from employees where employee_id = 150);


문제 : 직종이 IT_PROG직원들의 평균 급여보다 많이 받는 직원의 이름, 직종, 급여를 조회하시오.

select last_name, job_id, salary
from employees
where salary > ( select avg(salary) from employees where job_id like 'IT_PROG');

문제 : 최소 급여가 20부서의 급여보다 많이 받는 부서의 최소급여를 조회하시오.

SELECT department_id, min(salary)
FROM employees
HAVING min(salary) > (SELECT min(salary)
            FROM employees
            WHERE department_id = 20)
GROUP BY department_id;

문제 : 직종별로 평균 급여가 가장 적은 직종은?

select min(avg(salary))
from employees
group by job_id;

문제 : 평균 급여가 가장 적은 업무의 평균 급여는?

select job_id, avg(salary)
from employees
group by job_id
having avg(salary) = (select min(avg(salary)) 
	from employees 
	group by job_id);

문제 : Chen과 같은 직종에 근무하는 직원의 이름, 직종, 급여를 조회하시오

select last_name, job_id, salary
from employees
where job_id = (select job_id
		from employees 
		where last_name = 'Chen');

문제 : King과 같은 직종에 근무하는 직원의 이름, 직종, 급여를 조회하시오

select last_name, job_id, salary
from employees
where job_id in (select job_id
					from employees
                    where last_name = 'King');

문제 : Abel이라는 사원이 받는 급여보다 더 많은 급여를 받는 사원의 이름과 급여를 출력하시오

// 현재 abel의 사원이 받는 급여를 모름!

위 결과를 토대로

라는 결과를 얻을 수 있음!

하지만 2개의 select문을 실행해야하는 불편함을 없애기 위해 서브쿼리를 사용!!

 

서브쿼리 목적

1. 특정 값을 모를 때 사용

2. 다양한 결과 값을 얻을 때 사용

 

서브쿼리

  • 문장안에 또다른 문장
  • group by절 이외에 서브쿼리 사용가능
  • select, order by절에서는 자주 사용을 안함
  • 모든 select문을 사용 가능
  • 서브쿼리 안에 서브쿼리가 사용가능

 

  • where/having절에서 사용하는 서브쿼리 주의 사항
    • 서브 쿼리는 괄호로 묶어서 사용
    • 비교 조건의 오른쪽에 서브쿼리를 넣음 == 연산자 옆에 서브쿼리를 넣음
    • order by절에서는 사용하지 않은걸 권장 => order by는 정렬하는 문법, 고로 값이 나오는 서브쿼리는 사용할 필요 없음
    • 단일 행 서브 쿼리에는 단일 행 연산자를 사용하고 다중 행 서브 쿼리에는 다중 행 연산자를 사용
      • 단일 행 연산자 ( =, >, <  등등)
      • 다중 행 연산자( in 과 같은 연산자)

where / having 에서 사용하는 서브쿼리 =>조건식의 값을 대체하기 위해 서브쿼리 사용

 

공통점 : where 과 having은 둘 다 조건절

 

where = 행의 조건

조건절(조건식) col 연산자 값

 

having = 그룹의 조건

그룹함수(col) 연산자 값


 

<< 서브쿼리 작성의 꿀팁 >> 

  1. 내가 뭘 모르는지 찾자 
    • ex) Abel의 급여를 몰랐음
  2. 모르는 값을 서브쿼리를 통해 찾자
  3. 모르는 값을 서브쿼리의 select-list절에 어떤 컬럼을 통해 찾을 것 인지 결정
    • ex) select salary -> Abel의 급여를 찾음
  4. 서브쿼리 값을 받아줄 메인쿼리의 컬럼을 결정
    • ex) where salary <- 서브 쿼리 결과인 salary 값을 받음
    • 메인 쿼리에서 컬럼을 결정 할 때 =>반드시 데이터 타입이 같아야함!!!!!! 
    • 단, 컬럼 이름은 틀려도 상관이 없음. 그러나 대부분 두개의 컬럼이 이름이 같음
  5. 서브쿼리의 결과에 따라 비교연산자를 사용하자
    • 한 개 값을 넘겨줄때는 =, > 와 같은 단일 연산자를 사용
    • 복수 개 값을 넘겨줄때는 in과 같은 복수연산자를 사용

서브쿼리 예시

select last_name, job_id, salary
from employees
where salary = (select min(salary)
from employees);

왼쪽 : 서브쿼리만 실행, 오른쪽 : 전체 코드 실행


예시))

테이블 값 10, 20, 30, 40, 50, 60 

서브쿼리 결과(30,40)

 

  • in
    • in(30, 40) => 30, 40
  • all
    • > all : 서브쿼리 결과 전부 or 최대값(40) 보다 큰값을 찾아줌 : 50, 60
    • < all : 서브쿼리 결과 전부 or 최솟값(30) 보다 작은값을 찾아줌 : 10, 20
  • any
    • > any : 서브쿼리 결과 중 최솟값(30)보다 큰 값 : 40, 50, 60
    • < any : 서브쿼리 결과 중 최대값(40) 보다 작은 값 : 10, 20, 30

1. In (서브쿼리 결과 : 9000,6000,4200)

select employee_id, last_name, job_id, salary
from employees
where salary in (select salary
		from employees
		where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';


2. < any

 

select employee_id, last_name, job_id, salary
from employees
where salary < any (select salary
		from employees
		where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';


3. > any

select employee_id, last_name, job_id, salary
from employees
where salary > any (select salary
		from employees
		where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';


4. < all

select employee_id, last_name, job_id, salary
from employees
where salary < all (select salary
		from employees
		where job_id = 'IT_PROG')
and job_id <> 'IT_PROG'

5. > all


select employee_id, last_name, job_id, salary
from employees
where salary > all (select salary
		from employees
		where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';

 


31. Zlotkey와 동일한 부서에 근무하는 다른 모든 사원들의 사번 및 고용날짜를 출력하시오.

select last_name, employee_id, hire_date
from employees
where department_id = (select department_id
			from employees
			where last_name = 'Zlotkey')
and last_name != 'Zlotkey';

32. 회사 전체 평균 급여보다 더 급여를 많이 받는 사원들의 사번 및 이름을 출력하시오.

select employee_id, last_name
from employees
where salary > (select avg(salary)
		from employees);

33. 이름에 u가 포함이 되는 사원들과 동일 부서에 근무하는 사원들의 사번 및 이름을 출력하시오.

select employee_id, last_name
from employees
where department_id in (select department_id
	from employees
	where last_name like '%u%');

34. Ernst와 동일한 부서에 근무하는 사원중 급여가 5000보단 큰 사원의 이름과 급여를 출력하시오.

select last_name, salary
from employees
where department_id in (select department_id
		from employees
		where last_name = 'Ernst')
and salary > 5000;

//Ernst라는 동명이인이 있을 수 도 있어서 in사용


오후 [Java]

 

public class Ex01_이차원배열 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 5행 5열 크기의 2차월 배열 array 선언 및 생성
	
		int[][] array = new int[5][5];
		
		// 1~25까지 초기화
		// ex) array[0][0] = 1; array[4][4] = 25;
		

		int n = 1;
		for(int i =0; i<array.length; i++) {
			for(int j =0; j<array[i].length; j++)
			{
				array[i][j] = n++;				
				System.out.print(array[i][j] + "\t");
			}
			System.out.println();
		
		}
		

	}

}

public class Ex01_이차원배열 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 5행 5열 크기의 2차월 배열 array 선언 및 생성

		int[][] array = new int[5][5];

		// 1~25까지 초기화
		// ex) array[0][0] = 1; array[4][4] = 25;

		int n = 21;
		for (int i = 0; i < array.length; i++) {

			if (i % 2 == 0) {
				for (int j = 0; j < array[i].length; j++) {
					array[i][j] = n++;
				}
			} else {
				for (int j = array[i].length - 1; j >= 0; j--) {
					array[i][j] = n++;
				}
			}
			System.out.println();
		}
		
		for(int i = 0; i < array.length; i++) {
			for(int j = 0; j < array[i].length; j++) {
				System.out.print(array[i][j] + "\t");
			}
			System.out.println();
		}

	}

}

# 다른 답안

public class Ex01_이차원배열 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 5행 5열 크기의 2차월 배열 array 선언 및 생성

		int[][] array = new int[5][5];

		// 1~25까지 초기화
		// ex) array[0][0] = 1; array[4][4] = 25;

		int n = 21;
		for (int i = 0; i < array.length; i++) {
			for(int k=0; j=array[i].lenth; k <array[i].length; k++, j--{
            if(i%2==0)
            	array[i][k] = ++n;
            else
            	array[i][j-1] = ++n;
           }
		}
		
		for(int i = 0; i < array.length; i++) {
			for(int k = 0; k < array[i].length; k++) {
				System.out.print(array[i][k] + "\t");
			}
			System.out.println();
		}

	}

}

public class Ex01_이차원배열 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 5행 5열 크기의 2차월 배열 array 선언 및 생성

		int[][] array = new int[5][5];

		// 1~25까지 초기화
		// ex) array[0][0] = 1; array[4][4] = 25;

		int n = 21;
		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array[i].length; j++) {
				array[i][j] = n++;
			}

			System.out.println();

		}

		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array.length; j++) {
				System.out.print(array[j][i] + "\t");
			}
			System.out.println();
		}

	}

}

정렬 알고리즘

  • 개념
    • 원소들을 일정한 순서대로 열거하는 알고리즘
  • 종류
    • 버블 정렬
    • 선택 정렬
    • 삽입 정렬

Bubble sort

  • 두 인접한 원소를 비교하여 정렬하는 방법
  • 속도는 느리지만 코드가 단순
import java.util.Arrays;

public class Ex02_버블정렬 {

	public static void main(String[] args) {
		int[] arr = { 45, 7, 12, 82, 25 };
		System.out.println(Arrays.toString(arr));

		// 오름차순 정렬
		// arr.length : 5
		// 아래 연산 값에서 i+1 >> 5+1=6의 결과가 나오기 때문에 에러발생!!
		for (int i = 0; i < arr.length - 1; i++) {
			if (arr[i] > arr[i + 1]) {
				int temp = arr[i];
				arr[i] = arr[i + 1];
				arr[i + 1] = temp;
			}
		}
		System.out.println(Arrays.toString(arr));
	}

}

import java.util.Arrays;

public class Ex03_버블정렬연습 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = { 71, 5, 1, 12, 4 };
		System.out.println(Arrays.toString(arr));
		
		// 오름차순
//		for(int k=1; k<arr.length;k++) {
//			for(int i=0; i<arr.length-k;i++) {
//				if(arr[i]>arr[i+1]) {
//					int temp = arr[i];
//					arr[i] = arr[i+1];
//					arr[i+1] = temp;
//				}
//			}
//		}
//		System.out.println(Arrays.toString(arr));
		
		// 내림차순
		for (int k = 1; k < arr.length; k++) {
			for (int i = 0; i < arr.length - k; i++) {
				if (arr[i + 1] > arr[i]) {
					int temp = arr[i + 1];
					arr[i + 1] = arr[i];
					arr[i] = temp;
				}
			}
		}
		System.out.println(Arrays.toString(arr));
	}

}