예제 1
CREATE TABLE sales_record (
num INT PRIMARY KEY AUTO_INCREMENT,
name CHAR(10) NOT NULL,
sales INT NOT NULL,
today CHAR(10) NOT NULL
);
INSERT INTO sales_record (name, sales, today)
VALUES
('IU', 2000, '2023-05-01'),
('ailee', 4000, '2023-05-01'),
('yoona', 1000, '2023-05-01'),
('IU', 1500, '2023-04-31'),
('ailee', 300, '2023-04-31'),
('yoona', 4000, '2023-04-31'),
('IU', 5000, '2023-04-30'),
('yoona', 2500, '2023-04-30'),
('ailee', 2500, '2023-04-29'),
('ailee', 4000, '2023-04-28'),
('yoona', 3000, '2023-04-28'),
('IU', 9000, '2023-04-27'),
('ailee', 7000, '2023-04-27'),
('IU', 6000, '2023-04-26'),
('ailee', 2000, '2023-04-26'),
('yoona', 4000, '2023-04-26');
SELECT name, SUM(sales) total
FROM sales_record
GROUP BY name;
SELECT name, AVG(sales) average
FROM sales_record
GROUP BY name;
SELECT name, SUM(sales) total
FROM sales_record
GROUP BY name HAVING AVG(sales) >= 3000;
SELECT name, COUNT(today)
FROM sales_record
GROUP BY name;
SELECT name, MAX(sales)
FROM sales_record
GROUP BY name;
SELECT DISTINCT today
FROM sales_record
ORDER BY today;
SELECT COUNT(DISTINCT today) all_day
FROM sales_record;
예제 2
DROP TABLE professor;
DROP TABLE student;
CREATE TABLE professor(
pid INT PRIMARY KEY AUTO_INCREMENT,
pname VARCHAR(20) NOT NULL,
pmajor VARCHAR(20) NOT NULL
);
CREATE TABLE student (
sid INT PRIMARY KEY AUTO_INCREMENT,
sname VARCHAR(20) NOT NULL,
sgrade INT NOT NULL,
pid INT NOT NULL
);
INSERT INTO professor(pname, pmajor) VALUES
('james', 'computer'),
('jhone', 'math'),
('jane', 'english'),
('jason', 'kor');
INSERT INTO student(sname, sgrade, pid) VALUES
('smith', 3, 1),
('clock', 1, 2),
('jonadan', 2, 3),
('mike', 4, 1),
('brown', 2, 2),
('joe', 2, 3);
SELECT pname FROM professor NATURAL JOIN student WHERE sname IN ('joe', 'jonadan');
SELECT pname, sname FROM professor NATURAL JOIN student;
SELECT pname, sname FROM professor p LEFT OUTER JOIN student s ON p.pid = s.pid;
SELECT pname, COUNT(sname) FROM professor p LEFT OUTER JOIN student s ON p.pid = s.pid GROUP BY p.pid;
SELECT pname FROM professor p LEFT OUTER JOIN student s ON p.pid = s.pid WHERE s.sid IS NULL;
SELECT pname FROM professor p WHERE NOT EXISTS (SELECT * FROM student s WHERE p.pid = s.pid);
SELECT pname FROM professor p WHERE NOT p.pid IN (SELECT DISTINCT s.pid FROM student s);
SELECT sname FROM student s NATURAL JOIN professor p WHERE pmajor = 'computer';
SELECT sname FROM student s WHERE EXISTS (SELECT * FROM professor p WHERE s.pid = p.pid AND pmajor = 'computer');
SELECT pmajor, COUNT(sname) FROM professor p LEFT OUTER JOIN student s ON p.pid = s.pid GROUP BY pmajor;