[Udemy] The Magic of Aggregate Functions
The Ultimate MySQL Bootcamp 9강을 공부하며 정리한 내용입니다.
COUNT
데이터의 개수를 계산한다.
SELECT COUNT(author_fname) FROM books; //19
//How many distinct author fnames?
SELECT COUNT(DISTINCT author_fname) FROM books; //12
//How many distinct author names?
SELECT COUNT(DISTINCT author_fname, author_lname) FROM books;
//How many titles contain "the"?
SELECT count(title) FROM books WHERE title LIKE '%the%'; //6
GROUP BY
GROUP BY summarizes or aggregates identical data into single rows
title | author_lnames |
---|---|
The Namesake | Lahiri |
Norse Mythology | Gaiman |
American Gode | Gaiman |
Interpreter of Maladies | Lahiri |
A Hologram for the kin: A Novel | Eggers |
SELECT title, author_lname
FROM books
GROUP BY author_lnames
위와 같은 테이블이 있고 다음과 같은 쿼리문을 작성했을때, 결과는 다음과 같다.
title | author_lnames |
---|---|
The Namesake | Lahiri |
Norse Mythology | Gaiman |
A Hologram for the kin: A Novel | Eggers |
MIN, MAX
데이터의 최소값, 최대값을 찾는다.
SELECT MIN(released_year) FROM books; //1945
SELECT MAX(released_year) FROM books; //2017
-
What if I want the title of the longest OR shortest book?
SELECT MAX(pages), title FROM books;
only_full_group_by 에러가 나거나 잘못된 제목이 조회된다. 즉, MAX(pages)는 올바르게 찾지만, 다음으로 찾아야하는 title은 책들 중 첫번째 제목을 조회한다.- 해결방안1 SUBQUERY
단, 서브쿼리가 복잡해질수록 시간이 오래 걸린다.SELECT title, pages FROM books WHERE pages = (SELECT MAX(pages) FROM books);
- 해결방안2 ORDER BY, LIMIT
SUBQUEYRY를 사용하지 않고 MAX,MIN의 특징을 토대로 문제를 해결할 수 있다.SELECT * FROM books ORDER BY pages DESC LIMIT 1
- 해결방안1 SUBQUERY
MIN, MAX with GROUP BY
- Find the year each author published their first book
SELECT author_fname, author_lname, MIN(released_year)
FROM books
GROUP BY author_lname, author_fname;
- Find the longest page count for each author
SELECT MAX(pages), author_lname, author_fname
FROM books
GROUP BY author_lname, author_fname;
SELECT (author_fname, ' ', author_lname) AS 'author', MAX(pages) AS 'longest book'
FROM books
GROUP BY author_lname, author_fname;
SUM
데이터의 합계를 구한다.
- Sum all pages each author has written
SELECT author_fname, author_lname, SUM(pages)
FROM books
GROUP BY author author_lname, author_fname;
AVG
데이터의 평균을 구한다.
- Calculate the average stock quantity for books released in the same year
SELECT AVG(stock_quantity), released_year
FROM books
GROUP BY released_year;
- Calculate the average pages for for books written by the same author
SELECT author_lname, author_fname, AVG(pages)
FROM books
GROUP BY author_lname, author_fname;
Author And Source
이 문제에 관하여([Udemy] The Magic of Aggregate Functions), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@kaitlin_k/Udemy-The-Magic-of-Aggregate-Functions저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)