The Ultimate MySQL Bootcamp 9강을 공부하며 정리한 내용입니다.
데이터의 개수를 계산한다.
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 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 |
데이터의 최소값, 최대값을 찾는다.
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은 책들 중 첫번째 제목을 조회한다.
SELECT title, pages FROM books
WHERE pages = (SELECT MAX(pages) FROM books);
SELECT * FROM books ORDER BY pages DESC LIMIT 1
SELECT author_fname, author_lname, MIN(released_year)
FROM books
GROUP BY author_lname, author_fname;
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;
데이터의 합계를 구한다.
SELECT author_fname, author_lname, SUM(pages)
FROM books
GROUP BY author author_lname, author_fname;
데이터의 평균을 구한다.
SELECT AVG(stock_quantity), released_year
FROM books
GROUP BY released_year;
SELECT author_lname, author_fname, AVG(pages)
FROM books
GROUP BY author_lname, author_fname;
Aggregate functions are a powerful tool in database management systems that allow for the manipulation of large data sets. From counting and averaging to summing and grouping, aggregate functions can help https://magicalkatrina.com/ uncover valuable insights and trends in their data. By combining multiple data points into a single result, aggregate functions can simplify complex calculations and provide a more comprehensive understanding of business performance. Whether you're analyzing sales figures or tracking customer behavior, understanding the magic of aggregate functions can help you make more informed decisions and drive greater success in your business.