본문 바로가기
💾Database & Server/SQL

[SQL] SQL Cookbook - 02.쿼리 결과 정렬

by inbeom 2023. 9. 7.
728x90

참고

1. 지정한 순서대로 쿼리 결과 반환하기 

# ORDER BY
select ename, job, sal
	from emp
   where deptno = 10
   order by sal asc

 

2.  다중 필드로 정렬하기

order by 절에서 쉼표로 구분하여 여러 열을 나열하면 제일 왼쪽 열부터 우선순위를 가지고 정렬된다.

# ORDER BY
select empno, deptno, sal, ename, job
	from emp
   order by deptno, sal desc

 

3.  부분 문자열로  정렬하기

substr() 함수를 사용하여 문자열을 추출해 정렬할 수 있다.

# ORDER BY, SUBSTR
select ename, job
	from emp
   order by substr(job, length(job)-1)

 

4.  혼합 영숫자 데이터 정렬하기

replace() : 문자열 치환. REPLACE(원본_문자열, 찾을_문자열, 교체할_문자열)

translate() : 문자를 다른 문자로 변경. TRANSLATE(원본_문자열, 변환_대상_문자, 변환_할_문자)

# REPLACE, TRANSLATE

/*DEPTNO로 정렬*/
select data
	from V
   order by replace(data,
   		replace(
   		translate(data, '0123456789', '#########'), '#', ''), '')
                    
/*ENAME으로 정렬*/
select data
	from V
   order by replace(
   		translate(data, '0123456789', '#########'), '#', '')

 

5. 정렬할 때 null 처리하기

order by 절은 왼쪽 조건(컬럼)이 우선순위가 높다.

# NULL이 아닌 COMM을 우선 오름차순 정렬하고, 마지막에 NULL나타냄
select ename, sal, comm
	from (
   select ename, sal, comm,
   		case when comm is null then 0 else 1 end as is_null
    from emp
		) x
    order by is_null desc.comm


# NULL을 처음에 나타낸 후, NULL이 아닌 COMM은 내림차순 정렬
select ename, sal, comm
	from (
   select ename, sal, comm,
   		case when comm is null then 0 else 1 end as is_null
    from emp
    	 ) x
    order by is_null, comm desc

 

6. 데이터 종속 키 기준으로 정렬하기

job이 'SALESMAN'이면 comm 아니면 sal로 정렬

# ORDER BY, CASE
select ename, sal, job, comm
	from emp
   order by case when job = 'SALESMAN' then comm else sal end

 

 

 

 

reference.

[SQL Cookbook] - 한빛미디어 

728x90