๐ŸŽ๋งˆ์ง€๋ง‰ ์—ฐ์Šต ๋ฌธ์ œ!

์ฝ”๋“ฑ์–ดยท2024๋…„ 11์›” 22์ผ
0

์‚ฌ์ „์บ ํ”„

๋ชฉ๋ก ๋ณด๊ธฐ
11/19

์ƒํ’ˆ(products) ํ…Œ์ด๋ธ”

idnameprice
1๋žฉํ†ฑ1200
2ํ•ธ๋“œํฐ800
3ํƒ€๋ธ”๋ ›400

์ฃผ๋ฌธ(orders) ํ…Œ์ด๋ธ”

idproduct_idquantityorder_date
101122023-03-01
102212023-03-02
103352023-03-04

ํ…Œ์ด๋ธ” ์ž‘์„ฑ, ๋ฐ์ดํ„ฐ ์‚ฝ์ž… ์ฟผ๋ฆฌ

์ƒํ’ˆ(products)

create table products  
(
    id int unsigned,
    name varchar(10),
    price int unsigned
);

insert into products (id, name, price)values
(1, "๋žฉํ†ฑ", 1200),
(2, "ํ•ธ๋“œํฐ", 800),
(3, "ํƒ€๋ธ”๋ ›", 400);

์ฃผ๋ฌธ(orders)

create table orders   
(
	id int unsigned,
	product_id int unsigned,
    quantity int unsigned,
    order_date date
);

insert into orders (id, product_id, quantity, order_date)values
(101, 1, 2, "2023-03-01"),
(102, 2, 1, "2023-03-02"),
(103, 3, 5, "2023-03-04");

์—ฐ์Šต๋ฌธ์ œ

  1. ๋ชจ๋“  ์ฃผ๋ฌธ์˜ ์ฃผ๋ฌธ ID์™€ ์ฃผ๋ฌธ๋œ ์ƒํ’ˆ์˜ ์ด๋ฆ„์„ ๋‚˜์—ดํ•˜๋Š” ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”!
select o.id, p.name
from orders o left join products p
on o.product_id = p.id;
  1. ์ด ๋งค์ถœ(price * quantity์˜ ํ•ฉ)์ด ๊ฐ€์žฅ ๋†’์€ ์ƒํ’ˆ์˜ ID์™€ ํ•ด๋‹น ์ƒํ’ˆ์˜ ์ด ๋งค์ถœ์„ ๊ฐ€์ ธ์˜ค๋Š” ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”!
select o.product_id, sum(p.price * o.quantity) as total_sales
from orders o left join products p
on o.product_id = p.id
group by o.product_id
order by total_sales desc limit 1;
  1. ๊ฐ ์ƒํ’ˆ ID๋ณ„๋กœ ํŒ๋งค๋œ ์ด ์ˆ˜๋Ÿ‰(quantity)์„ ๊ณ„์‚ฐํ•˜๋Š” ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”!
select o.product_id, sum(o.quantity) as total_quantity
from orders o left join products p
on o.product_id = p.id
group by o.product_id;
  1. 2023๋…„ 3์›” 3์ผ ์ดํ›„์— ์ฃผ๋ฌธ๋œ ๋ชจ๋“  ์ƒํ’ˆ์˜ ์ด๋ฆ„์„ ๋‚˜์—ดํ•˜๋Š” ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”!
select p.name
from orders o left join products p
on o.product_id = p.id
where order_date > "2023-03-03";
  1. ๊ฐ€์žฅ ๋งŽ์ด ํŒ๋งค๋œ ์ƒํ’ˆ์˜ ์ด๋ฆ„์„ ์ฐพ๋Š” ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”!
select p.name 
from orders o 
left join products p on o.product_id = p.id 
group by p.id, p.name
order by sum(o.quantity) desc
limit 1;
  1. ๊ฐ ์ƒํ’ˆ ID๋ณ„๋กœ ํ‰๊ท  ์ฃผ๋ฌธ ์ˆ˜๋Ÿ‰์„ ๊ณ„์‚ฐํ•˜๋Š” ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”!
select p.id, avg(o.quantity) as avg_quantity
from orders o 
left join products p on o.product_id = p.id 
group by p.id;
  1. ํŒ๋งค๋˜์ง€ ์•Š์€ ์ƒํ’ˆ์˜ ID์™€ ์ด๋ฆ„์„ ์ฐพ๋Š” ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”!
select p.id, p.name 
from products p 
left join orders o on p.id = o.product_id 
where o.id is NULL;
profile
์ •ํ˜•ํ™”๋˜์ง€ ์•Š์€ ๋‚  ๊ฒƒ์˜ ์ƒ๊ฐ์„ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€