잘못된 사용
SELECT math_score
FROM scores
WHERE english_score = MIN(english_score)
올바른 사용
SELECT math_score
FROM scores
WHERE english_score = (SELECT MIN(english_score) FROM scores)
[기본 코드]
SELECT COUNT(column_name)
FROM table_name
WHERE condition
<예시>
[테이블 생성 및 값 삽입]
CREATE TABLE Customers(Id integer, Name varchar(100), Visits integer);
INSERT INTO Customers(Id, Name, Visits) values(1, "Amy", 1), (2, "Amy", 2), (3, "Jake", 3), (4, "Terry", 5), (5, NULL, NULL);
Table: Customers
Id | Name | Visits |
---|---|---|
1 | Amy | 1 |
2 | Amy | 2 |
3 | Jake | 3 |
4 | Terry | 5 |
5 | NULL | NULL |
[코드]
SELECT COUNT(*)
FROM Customers
[결과]
5
[코드]
SELECT COUNT(Name)
FROM Customers
[결과]
4
[코드]
SELECT COUNT(DISTINCT Name)
FROM Customers
[결과]
3
[기본 코드]
SELECT AVG(column_name)
FROM table_name
WHERE condition
<예시>
Table: Customers
Id | Name | Visits |
---|---|---|
1 | Amy | 1 |
2 | Amy | 2 |
3 | Jake | 3 |
4 | Terry | 5 |
5 | NULL | NULL |
[코드]
SELECT AVG(Visits)
FROM Customers
[결과]
2.75
[코드]
SELECT SUM(Visits) / COUNT(*)
FROM Customers
[결과]
2.2
[기본 코드]
SELECT SUM(column_name)
FROM table_name
WHERE condition
<예시>
Table: Customers
Id | Name | Visits |
---|---|---|
1 | Amy | 1 |
2 | Amy | 2 |
3 | Jake | 3 |
4 | Terry | 5 |
5 | NULL | NULL |
[코드]
SELECT SUM(visits)
FROM Customers
[결과]
11
[기본 코드]
SELECT MIN(column_name)
FROM table_name
WHERE condition
<예시>
Table: Customers
Id | Name | Visits |
---|---|---|
1 | Amy | 1 |
2 | Amy | 2 |
3 | Jake | 3 |
4 | Terry | 5 |
5 | NULL | NULL |
[코드]
SELECT MIN(visits)
FROM Customers
[결과]
1
[기본 코드]
SELECT MAX(column_name)
FROM table_name
WHERE condition
<예시>
Table: Customers
Id | Name | Visits |
---|---|---|
1 | Amy | 1 |
2 | Amy | 2 |
3 | Jake | 3 |
4 | Terry | 5 |
5 | NULL | NULL |
[코드]
SELECT MAX(visits)
FROM Customers
[결과]
5
참고:
https://www.w3schools.com/sql/sql_count_avg_sum.asp
https://www.w3schools.com/sql/sql_min_max.asp
https://docs.microsoft.com/en-us/sql/t-sql/functions/aggregate-functions-transact-sql?view=sql-server-ver15