DataBase/MySQL
[MySQL] 집계함수와 group by, having절 , rollup
자바칩 프라푸치노
2020. 11. 25. 15:17
<usertbl>
<buytbl>
기본적 쿼리 문의 순서이다.
select
from
WHERE
group by
having
order by
1. 1) 집계함수, group by - 합계 sum
userid별로 구매한 건수를 userid오름차순으로 출력하라ㅇ
1
2
3
4
5
|
-- sum() 집계함수, 집계함수가 나오면 무조건 group by가 나와야한다.
select userid, sum(amount)
from buytbl
group by userid -- userid별로 나타내겠다는 말
order by userid; -- userid 별로 asc로 출력하겠다는 말(오름차순)
|
cs |
2)평균 avg
사용자 아이디 별 평균 구매 건수를 내림 차순으로 출력하라
1
2
3
4
5
|
select userid as '사용자 아이디' , avg(amount) as '평균 구매 건수'
from buytbl
group by userid
order by avg(amount) desc;
|
cs |
3) 최대 최소 max min
usertbl에서 최대 키와 최소 키, 이름을 출력해라
1
2
3
4
5
6
|
select name, height
from usertbl
where height = ( select max(height)
from usertbl)
or height = ( select min(height)
from usertbl);
|
cs |
4) 집계함수와 having절
총 구매액이 1000 초과인 사람의 사용자 아이디와 총 구매액을
사용자 아이디 별로 구하는데 총 구매액 내림차순으로 출력하라
1
2
3
4
5
6
7
8
9
10
|
-- having 절
-- 총 구매액이 1000 만원 이상만 보고 싶다면 어떻게 해야할까
-- 조건이니 where절에 넣으면 될 것이라 생각하지만 where절에는 집계함수를 쓸 수 없다.
-- having절도 역시 조건절이다. 단, 그룹함수를 가지고 조건을 줄 수 있다.
select userid as '사용자 아이디' , sum(price * amount) as '총 구매액'
from buytbl
group by userid
having sum(price * amount)>1000
order by sum(price * amount) desc;
-- from -> where -> group by -> having -> select -> order by 순으로 실행됨
|
cs |
집계함수에서 조건을 걸고 싶으면 having절을 사용해야함
5) rollup
groupname별로 소합계를 내준다.
1
2
3
4
5
|
select groupname, sum(price* amount)
from buytbl
group by groupname
with rollup;
|
cs |
groupname이 null인 총 구매액 180,
서적이 groupname인 총 구매액 120... 가다가
마지막에 전체 총 구매액을 내줌
2. 알리아스 as
1
2
3
4
5
|
select userid as '사용자 아이디', sum(amount) as '구매한 건수'
from buytbl
group by userid
order by userid;
|
cs |
as를 이용해서 컬럼에 이름을 붙여준다.
728x90