その先にあるもの…

[SQL] group by 기초 정리 본문

프로그래밍/SQL

[SQL] group by 기초 정리

specialJ 2017. 7. 21. 13:42
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#컬럼 값을 그룹핑하여 같은 값의 카운팅
Select vend_id, count(*) as num_prods
From products
Group by vend_id;
----------------------------------------------------------------------------
vend_id,num_prods
BRS01,    3
DLL01,    4
FNG01,    2
 
#group by절에는 원하는 만큼의 컬럼을 써서, 중첩 그룹을 만들 수 있다.
#select 안에서 수식을 사용한다면, group by에도 같은 수식을 사용해야 한다.
#그룸 함수 구문을 제외하고 select문에 있는 모든 컬럼은 group by절에 존재해야 한다.
#group by절은 wherer절 뒤에 order by절 앞에 와야 한다.
 
 
 
#그룹핑을 하고 결과 필터링하기
Select cust_id, count(*) as orders
From orders
group by cust_id
having count(*>= 2;
----------------------------------------------------------------------------
cust_id,orders
1000000001,2
 
 
 
#where에서 먼저 필더링한 결과 값을 그룹핑하고 필터링
Select vend_id, count(*) as num_prods
from products
where prod_price >= 4
group by vend_id
having count(2>= 2;
----------------------------------------------------------------------------
vend_id,num_prods
BRS01,3
FNG01,2
 
 
#정렬
Select order_num, count(*) as items
from orderitems
group by order_num
having count(*>= 3
order by items, order_num;
----------------------------------------------------------------------------
order_num,items
20006,3
20009,3
20007,5
20008,5
 
cs


'프로그래밍 > SQL' 카테고리의 다른 글

[SQL] postgresql 원격 접속  (0) 2018.02.07
[SQL] sql union 기초 정리  (0) 2017.07.21
[SQL] sql 서브쿼리 기초 정리  (0) 2017.07.21
[SQL] MySQL error  (0) 2017.07.11
[SQL] MySql bulk insert  (0) 2017.07.11
Comments