[SQL] MYSQL 16

SUNGJIN KIM·2023년 8월 9일

SQL

목록 보기
6/8
post-thumbnail

오늘의 목표

SQL 강의 듣기 (16강)
과제 및 요약 내용 정리하기


강의 내용

집계 함수 (Aggregate Functions)

  • 어떤 그룹에 대하여 다양한 형태의 집계값 계산
종류설명
count()개수
sum()합계
min()최소
max()최대
avg()평균

count()

  • 레코드의 개수를 세주는 함수
select count(*) from Customer;

select count(*) from Customer c inner join SalesOrder so
	on (c.CustomerID = so.CustomerID)
where
	c.CountryRegion='United States';

count distinct

  • 별개의, 각각의 라는 뜻을 가지고 있음
select
	count(*) as Customers,
	count(distinct CountryRegion) as Countries,
	count(distinct City) as Cities
from Customer;

집계 함수들

select
	sum(SubTotal) as Order_Total,
	max(UnitPrice) as Max_Price,
	min(UnitPrice) as Min_Price,
	avg(UnitPrice) as Avg_Price
from SalesOrderDetail
where SalesOrderID = 71780;

형 변환(cast)

  • 갯수가 많아 나누게되면 소수점단위로 나와야하는데, 정수형으로 나오게 됨
    • avg 같은 경우 소수점 단위로 결과가 나오게 됨.
    • 정수-소수 로 진행을 하면 값이 달라질 수 있음
  • avg 함수는 형 변환이 필요하다.
select avg(OrderQty)
from SalesOrderDetail sod inner join Product p
on (sod.ProductID = p.ProductID)
where p.ProductCategoryID = 6;

select avg(cast(OrderQty as numeric(5,0)))
from SalesOrderDetail sod inner join Product p on
(sod.ProductID = p.ProductID)
where p.ProductCategoryID = 6;

isnull()

  • null 값인 경우 대체하는 값 지정
  • is null, is not null은 where 절에 쓰임
select
	ProductID, size,
	isnull(size, 'N/A') as Null_Size
from Product;
  • 문자열 연결 연산(+)의 경우 한쪽이 null이면 결과도 null
select
	AddressLine1, AddressLine2,
	AddressLine1 + ' ' + AddressLine2 as Full_Addr1,
	isunll(AddressLine1,'') + ' ' +
	isnull(AddressLine2,'') as Full_Addr2
from Customer;

[과제] 쿼리 작성하기

  1. ‘Road Bikes’ 제품 카테고리로 등록된 제품의 총 수와 평균 판매가(ListPrice)
select
    count(p.ProductID) as Cnt,
    avg(p.ListPrice) as Avg_ListPrice
from
    Product p inner join ProductCategory pc
    on (p.ProductCategoryID = pc.ProductCategoryID)
where pc.Name = 'Road Bikes';

  1. 남성 (Title=’Mr.’)이 주문한 총 주문 건 수
select
    count(*) as Tot_Orders
from
    SalesOrder so inner join Customer c
    on (so.CustomerID = c.CustomerID)
where c.title = 'Mr.'

  1. 영국(’United Kingdom’) 에서 주문한 총 주문 건수와 총 주문 금액
select
    count(distinct so.SalesOrderID) as Tot_Orders,
    sum(sod.SubTotal) as Tot_Amount
from
    SalesOrder so inner join SalesOrderDetail sod
    on (so.SalesOrderID = sod.SalesOrderID)
    inner join Customer c
    on (so.CustomerID = c.CustomerID)
where c.CountryRegion = 'United Kingdom'

profile
#QA #woonmong

0개의 댓글