본문 바로가기

TOOL/MySQL

MySQL - count , group by

반응형
count( )

 

 

books 테이블의 데이터 갯수는??

select count(*)
from books;
-- 19개

 

 

 

author_fname의 갯수는?

 

select count( distinct author_fname )
from books;
-- 12개

 

 

 

책 제목에 the라고 들어있는 책은 몇개인가요?

 

select count( * )
from books
where title like '%the%';

 

 

 

 

group by

 

 

 

pandas와 마찬가지로 MySQL에서도 group by를 사용 할 수 있다.

 

" ~~별로 " 이런 문구에 사용하기 적합하다.

 

또한, group by는 컬럼1개, 2개, 3개 등등 상관없이 여러개 가능하다.

 

 

 

author_lname 별로, 몇권의 책을 썻는지, author_lname과 cnt라는 컬럼으로 데이터를 가져오시오

 

select author_lname, count( * ) as cnt
from books
group by author_lname;

 

 

 

full_name 별로, 각각 몇권의 책을 썻는지 full_name과 책의 갯수를 cnt라는 컬럼으로 가져오세요

select concat_ws(' ', author_fname, author_lname) as full_name,  count( * ) as cnt
from books
group by full_name;

 

 

위 설명과 마찬가지로 group by는 컬럼1개, 2개, 3개 등등등 상관없이 여러개 가능하다.

 

select author_fname, author_lname, count(*) as cnt 
from books
group by author_fname, author_lname;

반응형