[DBMS] SQL 기본 문법 - SELECT 문 2

류재성's avatar
Aug 11, 2024
[DBMS] SQL 기본 문법 - SELECT 문 2
 

1. ORDER BY

💡
ORDER BY는 결과가 출력되는 순서를 지정한다. ASC는 Ascending의 약자로 오름차순을 의미하고, DESC 는 Descending의 약자로 내림차순을 의미한다. 생락한다면 기본은 ASC 정렬이다.
 
select mem_id, mem_name, debut_date from member order by debut_date asc;
 
notion image
 
select mem_id, mem_name, debut_date from member order by debut_date desc;
 
notion image
 
💡
ORDER BY 절은 쿼리가 모두 실행된 이후 실행되기 때문에 쿼리의 가장 마지막에 위치한다.
 
notion image
 
ORDER BY 절이 WHERE 절 앞에 위치하면 오류가 발생한다.
 
select mem_id, mem_name,debut_date,height from member where height >= 164 order by height desc;
 
notion image
 
 
select mem_id, mem_name,debut_date,height from member where height order by height desc, debut_date asc;
 
ORDER BY 는 여러 개의 열로 설정할 수 있다.
 

2. LIMIT

💡
LIMIT 는 출력하는 개수를 제한한다.
 
select mem_name,debut_date from member order by debut_date desc limit 3;
notion image
 
limit 를 사용해서 출력할 개수를 정할 수 있다.
 
select mem_name,debut_date from member order by debut_date desc limit 3,2;
 
notion image
 
💡
limit 에 숫자를 두 개를 사용하면 시작 인덱스를 정할 수 있다. 첫 숫자는 시작하는 인덱스 , 두 번째 숫자는 출력할 개수를 지정한다. 인덱스는 0부터 시작하기 때문에 limit 3,2 는 4번째 행부터 2개를 출력한다는 의미이다.
 

3. DISTINCT

💡
DISTINCT는 중복된 데이터를 제거하고 하나만 출력한다.
 
select addr from member;
notion image
 
select distinct addr from member;
 
notion image
 
DISTINCT 를 사용하면 중복된 값을 제외한 하나의 값만 출력한다.
 

4. GROUP BY

💡
GROUP BY 절은 그룹으로 묶어주는 역할을 한다.
 
GROUP BY 절을 사용할 때는 그룹화된 결과에 포함되는 모든 컬럼이 GROUP BY 절에 포함되거나, 집계 함수(예: SUM, COUNT, AVG 등)를 통해 그룹화된 데이터를 처리해야 한다.
 
select mem_id,amount from buy order by mem_id asc;
notion image
 
 
select mem_id,SUM(amount) from buy group by mem_id;
 
notion image
 
GROUP BY 절을 사용했을 때 함께 출력될 컬럼도 함께 처리해준다.
 
💡
GROUP BY 와 함께 사용되는 집계 함수는 다음과 같다. SUM() : 합계를 구한다. AVG() : 평균을 구한다. MIN() : 최소값을 구한다. MAX() : 최대값을 구한다. COUNT() : 행의 개수를 구한다. COUNT(DISTINCT) : 행의 개수를 구한다.(중복은 1개로 인정한다.)
 
select mem_id as "회원 아이디", sum(amount) as "총 구매 개수" from buy group by mem_id;
 
notion image
 
별칭을 사용할 수 있다.
 
select mem_id as "회원 아이디", sum(price*amount) as "총 구매 금액" from buy group by mem_id ;
 
notion image
 
구매한 총 금액을 계산할 수도 있다.
 

5. HAVING

💡
HAVING 절은 SQL에서 그룹화된 데이터에 대한 조건을 필터링하는 데 사용된. HAVING 절은 주로 GROUP BY 와 함께 사용되며, GROUP BY 절로 그룹화된 각 그룹에 대해 조건을 적용할 때 사용된. HAVING 절은 WHERE 절과 비슷한 역할을 하지만, 중요한 차이점은 HAVING 은 그룹화된 결과에 적용된다는 점이다.
 
select mem_id as "회원 아이디", sum(price*amount) as "총 구매 금액" from buy group by mem_id ;
 
notion image
 
이 결과에서 구매액이 1000 이상인 회원에게만 사은품을 증정하려면 어떻게 해야 할까?
 
select mem_id as "회원 아이디", sum(price*amount) as "총 구매 금액" from buy where sum(price*amount) group by mem_id ;
 
notion image
 
where 절을 사용해서 조건을 필터링하면 오류가 발생한다. 이때 having 을 사용한다.
 
select mem_id as "회원 아이디", sum(price*amount) as "총 구매 금액" from buy group by mem_id having sum(price*amount)>1000 ;
 
notion image
Share article
RSSPowered by inblog