빅데이터 서비스 교육/데이터베이스

데이터베이스 SQL select문 작성

Manly 2022. 5. 1. 12:27
반응형

select * from employees;  from절의 테이블의 항목들 전부를 보여준다  --셀렉션

select employee_id, last_name, job_id from employees; 선택한 항목들에 대해만 보여준다

(select 절) +( * :전체, distinct: 중복값을 제외한다, alias: 별명) +  (from 절)
             ( column(select절)은 from절 테이블에 있는 항목이여야 한다.)
 


---select절+ from절 +where절

select 절 문법
    -  *
- distinct
- column: from절에 기술된 테이블 항목 이여야한다.
- alias : 별명
 column 별명 : 한칸 띄어서 별명을 쓴다
     column as 별명 : as를 쓰고 별명을 쓴다
 column "별명" : ""안의 내용(대,소문자,띄어쓰기) 그대로 별명이 출력된다
 column as "별명"
- 사측연산가능: +, -, *, /
- || -> 문자열을 연결
- 함수

from 절
  table명, dataset(테이블, 쿼리)

where절 (조건절)
  조건식: a = b where절에서는 식이 완성되어야 된다.

---distinct
107 rows selected.
SQL> select distinct job_id from employees;
19 rows selected.  
원래 107건의 job_id 가 나왔는데 중복값을 제외하는 distinct를 넣어서 중복제외 19건만 나온다.


SQL> select distinct department_id, job_id from employees;

job_id와 department_id 둘다 공통으로 중복되는 값을 제거하고 나타낸다.
    a  1   -->양쪽 모두 중복인 값만 제거  따라서   a   1
    a  2                                a   2    으로 표기된다.
    a  3                                a   3
    a  1



   
---alias
select last_name lnm, department_id deptid from employees; 
        (alias(별명): 테이블 네임 뒤에 한칸뛰고 설정 할 별명을 쓰면된다 
                                  ex)lnm, deptid)
 
select last_name as lnm, department_id as deptid from employees;
        (alias(별명): as를 이용해서도 가능)

select (last_name) as lnm, (department_id) deptid from employees;
   column alias(별명)을 쓸때  (column) + 별명도 가능하다. ()를 쓸수 있고, as는 생략 가능.

머리글은 소문자로 쓰던 대문자로쓰던 대문자로 나온다.
 위에서 lnm, deptid는 머리글로 대문자로 나온다.
 
 하지만 "lnm" 으로 쓰면 그대로 소문자로 "LNM"으로 쓰면 그대로 대문자로 나온다.
 -> select last_name as "lnm", department_id as "deptid" from employees;
"부 서"로 쓰면 부  서로 띄어쓰기가 된 상태 그대로 나온다.  
" " 안은 대문자, 소문자, 띄어쓰기,대소문자 섞어서 쓴 그대로 나온다.


---연산
select salary sal, salary * 12 anualsal from employees
사측 연산 가능(+,-,*,/): 위는 그냥 월급과 월급*12=연봉으로 두가지를 출력.

select 2+3*4 from dual;
     그냥 계산만 하고싶을때 dual(=임시의 빈테이블)을 이용해 계산 결과만 출력.


---문자열 연결
select first_name || last_name name from employees;
 이때 성과 이름이 합쳐져서 나온다.     || -> 문자열을 합치는 기호
select first_name ||' '|| last_name name from employees;
 이러면 성과 이름이 합쳐져서 나오는데 중간에 한칸 띄어지고 합쳐져서 나온다.
  
  

---from 절
select * from (select department_name from departments) dept;
 *는 테이블 전체가 나오는데 from절의 dataset을 보면 department_name밖에 없으니 department_name만 나온다.
 
 select * from departments;
 departments 전체 테이블이 나온다. (4개)

talbe1, table2, ...  from절에 테이블을 여러개 쓸수 있는데 이게 join? -나중에 배운다



---where 절
-조건식: a = b (완전한식)
-조건식은 and나 or로 연결한다.
-''(홑따옴표): 문자열, 날짜에 관련된 값을 비교할때 사용한다. -> 값을 비교할때!
-값을 비교시 대소문자를 구별한다. <-> select절의 머릿말(별명)은 대소문자 구별없이 대문자로 나타난다.
-연산의 우선순위
select 50+2*30 from dual;
  산술연산자   >  연결연산자(||)  > 비교조건 > is null, in > between
 곱>나눔>덧,뺄                                 
-and(범위): B>=x and x>=A -> B>=x>=A  ->  between A and B
-or     : a or b or c  ->  in (a,b,c): a거나 b거나 c인 것을 조회하라
-like   : 비슷한 자료를 조회
         % -> 모든값에 대해 길이에 상관없이 조회
 _ -> 모든값에 대해 한글자인것 조회
-null:     컬럼 + is null (값이 정해지지않은것 조회),     컬럼 + is not null (값이 정해진것 조회)
-order by : 정렬시킬때
 oreder by column asc(기본값 생략가능): 오름차순 ,    oreder by column desc: 내림차순   
          (select절에 있는 컬럼)   
 -group by 그룹지어준다
 -having
 
 
 select from where             -> from 절부터 1번  where 2번 group by 3번 having 4번
 group by/ having/ order by        select절 5번 order by 6번 순서로 컴퓨터는 실행한다.
-select절, from절 제외하고 생략이 가능하다

select emmployee_id empid, last_name lname from employees order by empid  
order by 뒤에 절에서 alias 별명으로도 실행이 되는가?   실행 순서에따라 order by 전에 별명이 지정되므로 가능하다.
order by 뒤에 1,2,3으로 쓸수도 있는데 각각 selecet 절에서 1번째 2번째 3번째 컬럼을 뜻한다.
 
 
select last_name, department_id from employees where department_id = 50;
   department_id = 50인 employees(직원들)의 last_name, department_id를 표시하는것
   ( 조건절 )


문제: job_id = IT_PROG인 직원의 이름(lastname),직종,급여를 조회하시오
select last_name, job_id, salary from employees where job_id = 'IT_PROG';   


문제: job_id = IT_PROG이면서 봉급이 5000이상인 직원의 이름(lastname),직종,급여를 조회하시오
select last_name, job_id, salary from employees where job_id = 'IT_PROG' and salary >= 5000;
job_id = IT_PROG이면서 5000이상인 -> 둘 다 만족하는 값 출력

문제: job_id = IT_PROG이거나 봉급이 5000이상인 직원의 이름(lastname),직종,급여를 조회하시오
select last_name, job_id, salary from employees where job_id = 'IT_PROG' or salary >= 5000;
job_id = IT_PROG이거나 봉급이 5000이상인 -> 둘 중 하나라도 만족하는 값 출력


문제: 급여가 5000~10000를 받는 직원의 이름(lastname),직종,급여를 조회하시오
select last_name, job_id, salary from employees where 10000>= salary and salary >= 5000;
select last_name, job_id, salary from employees where salary between 5000 and 10000;


문제: 부서가 50또는 80인 직원의 이름(lastname),부서,급여를 조회하시오
select last_name, department_id, salary from employees where department_id = 50 or department_id = 80;
select last_name, department_id, salary from employees where department_id in(50,80);


문제: 연봉이 50,000~ 100,000인 직원의 이름, 직종, 급여, 연봉 조회하시오
select last_name, job_id, salary, salary*12 연봉 from employees 
where salary*12 between 50000 and 100000;                 커미션 퍼센트가 있는데 여기에 포함안되었다.



select last_name, department_id, salary from employees where last_name like 'S%';
 
             where last_name like'S%' -> 이름이 S자로 시작하는 사람 (길이에 상관없이) 조회
             where last_name like '__i%'  1,2번째는 상관없이 3번째에 i가 들어가는것 조회
             where last_name like '%S%'   문자열 길이는 상관없고 S를 포함하는 이름을 조회
             where last_name like'%S'  이름이 S로 끝나는 사람 (길이에 상관없이) 조회
 
 
             where department_id = ''; (X)틀림  department_id가 정해지지 않은 값 (null)을 출력하고 싶으면
             where department_id is null;  department_id가 값이 없으면 출력한다.
             where department_id is not null; epartment_id가 값이 있으면 출력한다.
 
 


문제: 사원번호가 176인 사원의 이름과 부서 번호를 출력하시오
select last_name, department_id from employees where employee_id=176;

문제: 연봉이 120,000 이상되는 사원들의 이름 및 연봉을 출력하시오
select last_name, salary*12 from employees where salary*12 >= 120000;

문제: 30부서에서 근무하는 직원 중 직종이 'PU_MAN'인 직원의 사원번호, 이름, 직종, 급여, 부서번호를 조회하시오
select employee_id, last_name, job_id, salary, department_id from employees
where department_id = 30 and job_id = 'PU_MAN';

문제: 연봉이 150,000에서 200,000의 범위 이외인 사원들의 이름 및 연봉을 출력하시오. 단 연봉은 AnnSal로 출력하시오
select last_name, salary*12 "AnnSal" from employees where salary*12<150000 or salary*12>200000;
select last_name, salary*12 "AnnSal" from employees where salary*12 not between 150000 and 200000;

문제: 2003/01/01 일부터 2005/05/30일 사이에 고용된 사원들의 이름, 사번, 고용일자를 출력하시오. 고용일자 역순으로 정렬하시오
select last_name, employee_id, hire_date from employees 
where hire_date between '2003/01/01' and '2005/05/30' order by hire_date desc;
         순서로 정렬(오름차순) -> order by A (asc)생략가능   역순으로 정렬(내림차순) -> order by A desc
 

문제: 20이나 50부서에서 근무하는 모든 사원들의 이름 및 부서번호를 알파벳순으로 출력하시오
select last_name, department_id from employees where department_id=20 or department_id=50 order by last_name;
select last_name, department_id from employees where department_id in(20,50) order by last_name;


문제: 2006년도에 고용된 모든 사람들의 이름 및 고용일을 조회하라
select last_name, hire_date from employees where hire_date like'06%'; (연도 2006로 안될때 -> 06으로 표시해봐라)

반응형