블로그 이미지
꿈을 꾸는 꾸러기 YBHoon

카테고리

분류 전체보기 (81)
Oracle (71)
Installation (12)
SQL & PL/SQL (19)
Administration (12)
Backup & Recovery (14)
Tuning (10)
Modeling (0)
Architecture (0)
Real Application Clu.. (3)
Dataguard (0)
Etc (1)
운영체제 (7)
ETC (0)
Study (3)
Total
Today
Yesterday

달력

« » 2025.7
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

공지사항

태그목록

최근에 올라온 글

'Oracle/SQL & PL/SQL'에 해당되는 글 19건

  1. 2010.04.07 Top-N Query
  2. 2010.04.06 Top-N Analysis 1
  3. 2010.04.06 Subquery
  4. 2010.02.18 View
  5. 2010.02.18 Index
  6. 2010.02.17 데이터 무결성 제약조건
  7. 2010.02.17 DDL
  8. 2010.02.12 DML
  9. 2010.02.12 Subquery - 실습문제
  10. 2010.02.11 실습파일 내용

Top-N Query

Oracle/SQL & PL/SQL / 2010. 4. 7. 10:14


SQL> select empno, ename, sal,
  2    rank() over (order by sal desc) as rk
  3  from emp;

     EMPNO ENAME             SAL         RK
---------- ---------- ---------- ----------
      7839 KING             5000          1
      7788 SCOTT            3000          2
      7902 FORD             3000          2
      7566 JONES            2975          4
      7698 BLAKE            2850          5
      7782 CLARK            2450          6
      7499 ALLEN            1600          7
      7844 TURNER           1500          8
      7934 MILLER           1300          9
      7521 WARD             1250         10
      7654 MARTIN           1250         10
      7876 ADAMS            1100         12
      7900 JAMES             950         13
      7369 SMITH             800         14

14 rows selected.

 

SQL> select empno, ename, sal,
  2    dense_rank() over (order by sal desc) as rk
  3  from emp;

     EMPNO ENAME             SAL         RK
---------- ---------- ---------- ----------
      7839 KING             5000          1
      7788 SCOTT            3000          2
      7902 FORD             3000          2
      7566 JONES            2975          3
      7698 BLAKE            2850          4
      7782 CLARK            2450          5
      7499 ALLEN            1600          6
      7844 TURNER           1500          7
      7934 MILLER           1300          8
      7521 WARD             1250          9
      7654 MARTIN           1250          9
      7876 ADAMS            1100         10
      7900 JAMES             950         11
      7369 SMITH             800         12

14 rows selected.

 

SQL> select empno, ename, sal, rownum
  2  from emp;

     EMPNO ENAME             SAL     ROWNUM
---------- ---------- ---------- ----------
      7369 SMITH             800          1
      7499 ALLEN            1600          2
      7521 WARD             1250          3
      7566 JONES            2975          4
      7654 MARTIN           1250          5
      7698 BLAKE            2850          6
      7782 CLARK            2450          7
      7788 SCOTT            3000          8
      7839 KING             5000          9
      7844 TURNER           1500         10
      7876 ADAMS            1100         11
      7900 JAMES             950         12
      7902 FORD             3000         13
      7934 MILLER           1300         14

14 rows selected.

 

SQL> select a.*, rownum
  2  from (select empno, ename, sal from emp order by sal desc) a;

     EMPNO ENAME             SAL     ROWNUM
---------- ---------- ---------- ----------
      7839 KING             5000          1
      7788 SCOTT            3000          2
      7902 FORD             3000          3
      7566 JONES            2975          4
      7698 BLAKE            2850          5
      7782 CLARK            2450          6
      7499 ALLEN            1600          7
      7844 TURNER           1500          8
      7934 MILLER           1300          9
      7521 WARD             1250         10
      7654 MARTIN           1250         11
      7876 ADAMS            1100         12
      7900 JAMES             950         13
      7369 SMITH             800         14

14 rows selected.

 

SQL> select a.*, rownum
  2  from (select empno, ename, sal from emp order by sal desc) a
  3  where rownum = 1;

     EMPNO ENAME             SAL     ROWNUM
---------- ---------- ---------- ----------
      7839 KING             5000          1

 

SQL> select a.*, rownum
  2  from (select empno, ename, sal from emp order by sal desc) a
  3  where rownum = 5;

no rows selected

 

SQL> select empno, ename, sal,
  2  rank() over (order by sal desc) as rk
  3  from emp
  4  where rk = 5;
where rk = 5
      *
ERROR at line 4:
ORA-00904: "RK": invalid identifier

 

SQL> select *
  2  from (select empno, ename, sal,
  3  rank() over (order by sal desc) as rk
  4  from emp)
  5  where rk = 5;

     EMPNO ENAME             SAL         RK
---------- ---------- ---------- ----------
      7698 BLAKE            2850          5

 

SQL> select empno, ename, sal,
  2  dense_rank() over (order by sal desc) as rk
  3  from emp
  4  where rk = 5;
where rk = 5
      *
ERROR at line 4:
ORA-00904: "RK": invalid identifier

 

SQL> select *
  2  from (select empno, ename, sal,
  3  dense_rank() over (order by sal desc) as rk
  4  from emp)
  5  where rk = 5;

     EMPNO ENAME             SAL         RK
---------- ---------- ---------- ----------
      7782 CLARK            2450          5

 

SQL> select a.*, rownum
  2  from (select empno, ename, sal from emp order by sal desc) a
  3  where rownum <= 5;

     EMPNO ENAME             SAL     ROWNUM
---------- ---------- ---------- ----------
      7839 KING             5000          1
      7788 SCOTT            3000          2
      7902 FORD             3000          3
      7566 JONES            2975          4
      7698 BLAKE            2850          5

5 rows selected.

 

SQL> select *
  2  from (select empno, ename, sal,
  3    rank() over (order by sal desc) as rk
  4      from emp)
  5  where rk <=5;

     EMPNO ENAME             SAL         RK
---------- ---------- ---------- ----------
      7839 KING             5000          1
      7788 SCOTT            3000          2
      7902 FORD             3000          2
      7566 JONES            2975          4
      7698 BLAKE            2850          5

5 rows selected.

 

SQL> select *
  2  from (select empno, ename, sal,
  3    dense_rank() over (order by sal desc) as rk
  4      from emp)
  5  where rk <=5;

     EMPNO ENAME             SAL         RK
---------- ---------- ---------- ----------
      7839 KING             5000          1
      7788 SCOTT            3000          2
      7902 FORD             3000          2
      7566 JONES            2975          3
      7698 BLAKE            2850          4
      7782 CLARK            2450          5

6 rows selected.

 

SQL> select *
  2  from (select a.*, rownum rnum
  3    from (select empno, ename, sal
  4      from emp order by sal desc) a
  5    where rownum <= 10)
  6  where rnum >= 6;

     EMPNO ENAME             SAL       RNUM
---------- ---------- ---------- ----------
      7782 CLARK            2450          6
      7499 ALLEN            1600          7
      7844 TURNER           1500          8
      7934 MILLER           1300          9
      7521 WARD             1250         10

5 rows selected.

'Oracle > SQL & PL/SQL' 카테고리의 다른 글

Top-N Analysis  (1) 2010.04.06
Subquery  (0) 2010.04.06
View  (0) 2010.02.18
Index  (0) 2010.02.18
데이터 무결성 제약조건  (0) 2010.02.17
Posted by YBHoon
, |

Top-N Analysis

Oracle/SQL & PL/SQL / 2010. 4. 6. 16:45


- 주의 사항
Where 절에는 Alias를 사용할 수 없다. 이유는?
The values in the select list do not "exist" before the where clause is executed.
The order of execution semantically is:
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY




* TOP-N 분석

 

   ㄴ 최대값 , 최소값 => N(갯수)

   ㄴ rownum => insert할때 자동으로 삽입 + inline view

   ㄴ 참고 사이트 : http://www.oracle.com/technology/oramag/oracle/07-jan/o17asktom.html

   ㄴ 형식

SELECT 컬럼명,..., ROWNUM FROM (SELECT 컬럼명,... from 테이블명  ORDER BY top_n_컬럼명)  WHERE ROWNUM <= n;


예제1> 연봉 가장 많은 5명

SELECT empno, sal FROM ( SELECT * FROM emp ORDER BY sal DESC) WHERE rownum <= 5;

         예제2> 입사일 기준으로 4 번째 부터 10번째까지 출력? ( 7 명 )
         select  empno , ename
                  from   (select  a.* , rownum rnum  from  (select *  from emp order by hiredate ) a
                  where rownum <= 10 ) where rnum >= 4;

http://blog.naver.com/iyearbook/150047915439



ROWNUM

 

ROWNUM은 SQL 쿼리결과 집합에 대한 순번(ROW의 SEQUENCE)을 나타내는 의사컬럼(가상의 COLUMN)이다.

 

용도는 TOP-N 분석에 유용하다.

 

select [column list], ROWNUM

from

    (select [column list]

     from tbl

     where [...]

     order by [TOP-N Column]

   )

where rownum <= 100

 

=> 서브쿼리에서 검색 및 sorting한 결과 집합의 상위 100개를 가져온다.

 

 

RANK() OVER ( [PARTITION BY column] ORDER BY column [NULL FIRST | NULL LAST] ) as rank

 

 OVER : 순위를 부여하기 위한 대상 집합의 정렬 기준과 분할 기준 정의

 PARTITION BY : value expression1을 기준으로 분할, 생략시 전체 집합 대상

예 ) rank() over(partition 반 order by 점수) 반에서의 점수의 등수

         => 반(partition column)의 데이타 별로 점수(order by column)에 대한 순위(rank())를 매김.
      rank() over(order by 점수) 전체에서의 점수의 등수

        => 모든 데이타(전체 row)에서 점수(order by column)에 대한 순위(rank())를 매김

 

ORDER BY : 각 분할내에서 데이터를 정렬하는 기준 칼럼 지정

NULL FIRST | NULL LAST : 정렬 결과에서 NULL 값의 위치 지정

 

DENSE_RANK()

 
ROW_NUMBER()
 
RANK()와 DENSE_RANK()와 ROW_NUMBER()의 차이 비교
RANK      DENSE_RANK    ROW_NUMBER
1            1                     1
2            2                     2
3            3                     3
3            3                     4
3            3                     5
6            4                     6
7            5                     7
8            6                     8

http://blog.naver.com/kdm707/10025917788



top-N 분석은 최대값이나 최소값을 가진 컬럼을 질의할 때 유용하게 사용되는 분석방법이다.
• inline view에서 ORDER BY 절을 사용할 수 있으므로 데이터를 원하는 순서로 정렬도 가능하다.
• ROWNUM 컬럼은 subquery에서 반환되는 각 행에 순차적인 번호를 부여하는 pseudo 컬럼이다.
• n값은 < 또는 >=를 사용하여 정의하며, 반환될 행의 개수를 지정한다.


【형식】
 SELECT 컬럼명,..., ROWNUM
 FROM (SELECT 컬럼명,... from 테이블명
       ORDER BY top_n_컬럼명)
        WHERE ROWNUM <= n;

여기서
 FROM 절 다음의 SELECT 문은 Top-N 분석 대상 컬럼에 대한 인라인 뷰의 정의
 ORDER BY :결과 집합의 정렬 순서 지정
 ROWNUM : 결과 집합에 대해 순차적인 번호를 할당하기 위한 의사 컬럼
 tOP-n_컬럼명 : 정렬 기준으로 사용하는 컬럼 또는 컬럼 집합

【예제】
SQL> select rownum as fastdate,ename,hiredate
  2  from (select ename,hiredate from emp
  3        order by hiredate desc)
  4  where rownum <= 5;
 
  FASTDATE ENAME      HIREDATE
---------- ---------- ------------
         1 ADAMS      23-MAY-87
         2 SCOTT      19-APR-87
         3 MILLER     23-JAN-82
         4 FORD       03-DEC-81
         5 KING       17-NOV-81
 
SQL>
다음 예는 TOP_N 분석 방법이다.
 
SQL> select deptno,ename,sal,rank_value
  2  from (select deptno, ename, sal,
  3        RANK() OVER (ORDER BY sal DESC) AS rank_value
  4        FROM emp)
  5  WHERE rank_value <=5;
 
    DEPTNO ENAME             SAL RANK_VALUE
---------- ---------- ---------- ----------
        10 KING             5000          1
        20 SCOTT            3000          2
        20 FORD             3000          2
        20 JONES            2975          4
        30 BLAKE            2850          5
 
SQL>
http://radiocom.kunsan.ac.kr/lecture/oracle/function/TOP_N.html


http://thdwns2.springnote.com/pages/1007064

'Oracle > SQL & PL/SQL' 카테고리의 다른 글

Top-N Query  (0) 2010.04.07
Subquery  (0) 2010.04.06
View  (0) 2010.02.18
Index  (0) 2010.02.18
데이터 무결성 제약조건  (0) 2010.02.17
Posted by YBHoon
, |

Subquery

Oracle/SQL & PL/SQL / 2010. 4. 6. 13:42

 

Overview
Subqueries can be used to answer queries such as "who has a salary more than Tom's". For such query, two queries have to be executed: the first query finds Tom's salary and the second finds those whose salary is greater than Tom's. Subquery is an approach provides the capability of embedding the first query into the other:  Oracle executes the subquery first, making the result of the sub query available to the main query and then executing the main query.

The syntax of subquery is

SELECT <column, ...>

FROM <table>

WHERE expression operator

    ( SELECT <column, ...>

       FROM <table>

      WHERE <condition>)

For example, the following statement answers the described query above.

    SQL> SELECT * FROM employee

         WHERE sal > (SELECT sal WHERE name='TOM');

Note that:

a subquery must be enclosed in the parenthesis.
a subquery must be put in the right hand of the comparison operator, and
a subquery cannot contain a ORDER-BY clause.
a query can contain more than one sub-queries.
In general, there are three types subqueries:

single-row subquery, where the subquery returns only one row.
multiple-row subquery, where the subquery returns multiple rows,.and
multiple column subquery, where the subquery returns multiple columns.
Single-row subqueries can only be used with single-row comparison operators, and multiple-row subqueries can be used only with multiple-row operators.  They are to be described separately in the following.


--------------------------------------------------------------------------------

Single-Row Subquery
The operators that can be used with single-row subqueires are =, >, >=, <, <=, and <>.

Group functions can be used in the subquery. For example, the following statement retrieve the details of the employee holding the highest salary.

SQL> SELECT * FROM employee

     WHERE sal = (SELECT MIN(sal) FROM employee);

Having-clause can also be used with the single-row subquery. For example, the following statement returns all departments in where the minimum salary is more than the minimum salary in the department 5.

SQL> SELECT dept_no, MIN(sal) FROM employee

     GROUP BY dept_no

  HAVING MIN(sal) > (

      SELECT MIN(sal)

        FROM employee

        WHERE dept_no = 5);


--------------------------------------------------------------------------------

Multiple-Row Subquery
Note the following statement is illegal, because the operator = cannot be used with subquery returns multiple rows.

SQL> SELECT name, sal FROM employee

  WHERE sal > (

      SELECT MIN(sal) FROM employee GROUP BY dept_no);

Some operators that can be used with multipe-row subqueries are:

IN, equal to any member in the list,
ANY, compare values to each value returned by the subquery.
For example, the following statement find the employees whose salary is the same as the minimum salary of the employees in some department.

SQL>  SELECT name, sal FROM employee

  WHERE sal IN (

      SELECT MIN(sal)

        FROM employee

        GROUP BY dept_no);

 

For example, the following statement find the employees whose salary is more than the minimum salary of the employees in any department.

SQL> SELECT name, sal FROM employee

  WHERE sal > ANY (

      SELECT MIN(sal)

        FROM employee

        GROUP BY dept_no);


--------------------------------------------------------------------------------

Multiple-Column Subquery
In multiple-column  subqueries, rows in the subquery results are evaluated in the main query in pair-wise comparison. That is, column-to-column comparison and row-to-row comparison.

For example, the following statement lists all items whose quantity and product id match to an item of order id 200.

SQL> SELECT order_id,  product_id, quantity

    FROM item

    WHERE (product_id, quantity) IN (

        SELECT  product_id, quantity FROM item WHERE order_it = 200)

    AND order_id = 200;

Note that you can put a subquery in the FROM clause in the main query.

For example, the following statement finds all employees in each department where their salary is above the average.

    SQL> SELECT a.name, a.sal, a.dept_no, b.salary_ave

        FROM employee a,

               (SELECT dept_no, AVE(sal) salary_ave

              FROM employee 

                GROUP BY dept_no)

        WHERE  a.dept_no = b.dept_no;

        AND a.sal > b.salary_ave;


--------------------------------------------------------------------------------

from ; http://www.comp.nus.edu.sg/~ooibc/courses/sql/dml_query_subquery.htm

'Oracle > SQL & PL/SQL' 카테고리의 다른 글

Top-N Query  (0) 2010.04.07
Top-N Analysis  (1) 2010.04.06
View  (0) 2010.02.18
Index  (0) 2010.02.18
데이터 무결성 제약조건  (0) 2010.02.17
Posted by YBHoon
, |

View

Oracle/SQL & PL/SQL / 2010. 2. 18. 12:10

- 원본 테이블에서 검색하고자 하는 컬럼만 보여주는 pseudo table로서
원본 데이터의 보안을 지키기 위해, 사용자의 편의성을 높이기 위해 사용함

- pseudo table이기 때문에 뷰를 지워도 원본 테이블은 지워지지 않고, index를 사용할 수 없다.

- MView는 대용량 자료를 사용하는데 편의를 위해 데이터를 갖고 있다.

- 연습문제 2
select a.no, a.emp_id, a.emp_name, b. dept_name
from (select rownum no, emp_id, emp_name, dept_code from temp) a, tdept b
where a.no between 3 and 6 and a.dept_code=b.dept_code

'Oracle > SQL & PL/SQL' 카테고리의 다른 글

Top-N Analysis  (1) 2010.04.06
Subquery  (0) 2010.04.06
Index  (0) 2010.02.18
데이터 무결성 제약조건  (0) 2010.02.17
DDL  (0) 2010.02.17
Posted by YBHoon
, |

Index

Oracle/SQL & PL/SQL / 2010. 2. 18. 11:45


- index = 주소록 (보조 기억장치에 데이터가 위치한 곳을 정리해 놓은 데이터의 주소록)

- 데이터를 관리하기 위한 목적으로 index를 만듦 (SQL 처리가 빨라지는 것은 부수적인 이득)

- where 조건절에 나오는 컬럼을 위주로 index를 작성한다.

- index를 생성하기 위해 먼저 시스템이 데이터 보호를 위해 lock을 하고 full scan을 한다.
이 때, 시스템에 부하가 높아지므로 데이터를 활용하지 않는 시간에 index를 작성하는게 바람직하다.

- index를 생성하는 과정 ; lock -> full scan -> sort -> block 기록 -> unlock

- 데이터 삽입시 index split으로 DML의 속도 저하
데이터의 추가시에 index도 업데이트를 해야 하며 이 과정에 index split이 발생
따라서 index가 많을 경우, 데이터 변경시에 index 업데이트로 인해 시스템에 부하가 많아짐
 
- 데이터 삭제시 테이블의 데이터는 지워지지만 index에는 데이터가 지워지지 않고
사용하지 않는 데이터로 표시되어 그대로 남아서 성능이 저하됨 => index rebuild를 해서 정리해줘야함

- index는 검색된 데이터의 블록이 많더라도 한번에 한 블록씩만 메모리로 불러들인다.
=> 총 데이터의 5% 미만일 경우에만 index의 성능이 좋다.

- index를 이용할 때, 보조 기억장치에서 한번에 읽어들이는 데이터의 양보다
데이터의 블록을 읽어들이기 위해 보조 기억장치를 액세스하는 횟수가 쿼리의 성능을 좌우한다.

- 따라서 전체 데이터 블록의 5% 이상의 횟수로 보조 기억장치의 블록을 액세스할 경우,
오라클의 optimizer는 인덱스를 사용하는 것이 비효율적이라고 판단하여 바로 보조기억장치를 검색함

- unique index는 내용이 중복되지 않으므로 사용하기 좋음 ; unique한 컬럼만 unique index로 지정할 수 있음

- 결합 index의 배합에 따라 index의 성능이 좌우됨

- descending index는 내림차순으로 정리함 ; max함수나 최근의 내용을 우선으로 검색할 때 좋음 (큰 값, 날짜별)

- index가 설정된 상태에서는 where로 검색할 때 index가 된 컬럼에 다른 함수는 지정하지 않는다.
대신 함수를 지정해야할 경우에는 함수 기반 인덱스를 지정한다.

'Oracle > SQL & PL/SQL' 카테고리의 다른 글

Subquery  (0) 2010.04.06
View  (0) 2010.02.18
데이터 무결성 제약조건  (0) 2010.02.17
DDL  (0) 2010.02.17
DML  (0) 2010.02.12
Posted by YBHoon
, |

- NOT NULL ; null 값을 받지 않음

- UNIQUE (UK) ; 중복되는 값을 허락하지 않음

- PRIMARY KEY (PK) ; not null과 unique의 결합

- FOREIGN KEY (FK) ; 부모와 자식 테이블에 index를 지정하면 검색시간을 줄일 수 있다.
on delete cascade ; 부모 테이블을 지우면 연결된 자식 테이블의 내용도 삭제됨
on delete set null ; 부모 테이블을 지우면 연결된 자식 테이블의 내용은 null이 됨

- CHECK ; 기본적으로 입력될 내용의 체크사항(제한사항)을 설정함

- constraint를 넣을 때는 컬럼 이름 뒤에 ,를 넣지 않는다. (다른 컬럼으로 인식되어 에러 발생)
마찬가지로 constraint를 복수로 넣을 때도 constraint 사이에 ,를 넣지 않는다.
constraint를 넣고 다른 컬럼으로 옮겨갈 때에 ,를 넣어서 구분한다.

'Oracle > SQL & PL/SQL' 카테고리의 다른 글

View  (0) 2010.02.18
Index  (0) 2010.02.18
DDL  (0) 2010.02.17
DML  (0) 2010.02.12
Subquery - 실습문제  (0) 2010.02.12
Posted by YBHoon
, |

DDL

Oracle/SQL & PL/SQL / 2010. 2. 17. 11:55

- 테이블 첫글자는 문자로 30자 이내로 같은 이름의 객체를 2개 이상 만들 수 없다.

- 오라클의 키워드(select, from, where...) 를 사용할 수 없다.

- 자료의 속성을 미리 예야하는 이유 : 메모리를 사전에 할당하기 위함
char ; 할당 받은 공간을 사용하지 않아도 반환하지 않음 (공간의 낭비 발생)
varchar2 ; 사용하지 않는 할당된 공간은 반환함 (업데이트시 row migration 발생)

- Create Table As ; 테이블을 복사하는 방법 - 필요한 자료만 추출해서 별도의 테이블을 만듬
CEATE table 테이블명 AS (서브쿼리 : select문)

- alter ; 컬럼 추가, 수정, 삭제가 가능

- drop ; 테이블 완전히 삭제, roll back 할 수 없다.

- 딕셔너리
DBA_ ; 모든 것을 볼 수 있음
ALL_ ; 자신이 만든 것과 액세스 권한이 있는 것만 볼 수 있음
USER_ ; 자신이 만든 것만 볼 수 있음

- select * from tab ; 사용하는 테이블을 검색함

'Oracle > SQL & PL/SQL' 카테고리의 다른 글

Index  (0) 2010.02.18
데이터 무결성 제약조건  (0) 2010.02.17
DML  (0) 2010.02.12
Subquery - 실습문제  (0) 2010.02.12
실습파일 내용  (0) 2010.02.11
Posted by YBHoon
, |

DML

Oracle/SQL & PL/SQL / 2010. 2. 12. 12:39

- insert, delete, update, merge

- where 조건문을 생략할 경우 모든 데이터에 영향을 끼칠 수 있으니 주의할 것!

- delete, truncate, drop의 차이
delete : 데이터만 지움, 공간은 그대로 남아 있음
truncate : 데이터와 공간을 지움 (DDL)
drop : 테이블을 완전히 삭제함 (DDL)

- DML을 사용 후 DDL, DCL을 사용하면 자동적으로 comitt이 되어버림 (오라클의 복구 방법이 있음)

'Oracle > SQL & PL/SQL' 카테고리의 다른 글

데이터 무결성 제약조건  (0) 2010.02.17
DDL  (0) 2010.02.17
Subquery - 실습문제  (0) 2010.02.12
실습파일 내용  (0) 2010.02.11
Subquery  (0) 2010.02.11
Posted by YBHoon
, |

- 학생테이블에서 이광훈 학생과 같은 학과 학생들의 이름과 학과 이름을 출력하세요.

SQL> select s.name, d.dname
from student s, department d
where s.deptno=d.deptno
and s.deptno=(select deptno from student where name='이광훈');

※ where d.deptno=(select deptno from student where name='이광훈')으로 조건을 입력할 경우
학과 이름이 이광훈 학생의 학과 이름으로 변경되어 "모든 학생들이 검색" 됨


- 101번 학과 학생들의 평균몸무게보다 적은 학생의 이름, 학과번호, 몸무게를 출력하세요.

SQL> select name, deptno, weight
from student
where weight < (select avg(weight) from student where deptno=101);


- 이광훈 학생의 학과의 평균몸무게보다 작은 학생들의 학생이름과 학생의 몸무게,
각 학생들의 학과이름과 지도교수 이름을 출력하세요.

SQL> select s.name, s.weight, d.dname, p.name
from student s, department d, professor p
where s.deptno=d.deptno and s.profno=p.profno(+) and
s.weight < (select avg(weight) from student
where deptno = (select deptno from student where name='이광훈'));

※ (+)가 빠질 경우, 지도교수가 없는 학생들은 검색에서 제외 됨


- temp, tdept 테이블을 사용하여 인천에 근무하는 직원의 사번과 성명을 구하세요.
SQL> select emp_id, emp_name
from temp
where dept_code in (select dept_code from tdept where area='인천');


- temp, tdept, tcom 테이블을 참고하여 부서별로 commission을 받는 인원수를 세는 쿼리를 작성하세요.

SQL> select d.dept_name, count(*)
from tdept d, temp e
where d.dept_code=e.dept_code
and emp_id in (select emp_id from tcom)
group by d.dept_name;


- temp 테이블에서 과장 중 가장 급여를 적게 받는 사람보다 많이 받는 사원들의
사번, 이름 급여를 출력하세요.

SQL> select emp_id, emp_name, salary
from tem
where salary > any (select salary from temp where lev='과장');


- temp 테이블에서 부서별로 최대 연봉을 구해서 연봉을 받는 사원의 부서코드, 사번, 이름, 급여를 출력하세요.

SQL> select dept_code, emp_id, emp_name, salary
from temp
where (dept_code,salary) in (select dept_code, max(salary) from temp group by dept_code);

'Oracle > SQL & PL/SQL' 카테고리의 다른 글

DDL  (0) 2010.02.17
DML  (0) 2010.02.12
실습파일 내용  (0) 2010.02.11
Subquery  (0) 2010.02.11
JOIN (ANSI JOIN)  (0) 2010.02.11
Posted by YBHoon
, |

-temp
emp_id,  emp_name,  birth_date,  dept_code,  emp_type,  use_yn,  tel,  holly,  salary,  lev

-tdept
dept_code,  dept_name,  paren_dept,  use_yn,  area,  boss_id

-tcom
work_year,  emp_id,  bonus_rate,  commle

-emp_level
lev,  from_sal,  to_sal,  from_age,  to_age

-student
studno,  name,  userid,  grade,  idnum,  birthdate,  tel,  height,  weight,  deptno,  profno

-professor
profno,  names,  userid,  position,  sal,  hiredate,  comm,  deptno

-department
deptno,  dname,  college,  loc

'Oracle > SQL & PL/SQL' 카테고리의 다른 글

DML  (0) 2010.02.12
Subquery - 실습문제  (0) 2010.02.12
Subquery  (0) 2010.02.11
JOIN (ANSI JOIN)  (0) 2010.02.11
JOIN (oracle JOIN) - 연습문제  (0) 2010.02.11
Posted by YBHoon
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함