중급 SQL Server
Ginger Grant
Instructor
SELECT COUNT(*) FROM Incidents
+-----------------+
|(No column name) |
+-----------------+
|6452 |
+-----------------+
COUNT(DISTINCT COLUMN_NAME)
SELECT COUNT(DISTINCT Country) AS Countries
FROM Incidents
+----------------+
|Countries |
+-----------------+
|3 |
+-----------------+
SELECT COUNT(DISTINCT Country) AS Countries,
COUNT(DISTINCT City) AS Cities
FROM Incidents
+----------------+-------------+
|Countries | Cities |
+-----------------+-------------+
|3 | 3566 |
+-----------------+-------------+
GROUP BY는 AVG(), MIN(), MAX() 등 다른 집계 함수와 마찬가지로 COUNT()와 함께 사용할 수 있습니다
ORDER BY 명령어로 결과를 정렬할 수 있습니다
ASC: 작은 값부터 정렬 (기본값)DESC: 큰 값부터 정렬-- Count the rows, subtotaled by Country
SELECT COUNT(*) AS TotalRowsbyCountry, Country
FROM Incidents
GROUP BY Country
+----------------------+-----------------+
|TotalRowsbyCountry | Country |
+----------------------+-----------------+
|5452 |us |
|750 |NULL |
|249 |ca |
|1 |gb |
+----------------------+-----------------+
-- Count the rows, subtotaled by Country
SELECT COUNT(*) AS TotalRowsbyCountry, Country
FROM Incidents
GROUP BY Country
ORDER BY Country ASC
+----------------------+-----------------+
|TotalRowsbyCountry | Country |
+----------------------+-----------------+
|750 |NULL |
|249 |ca |
|1 |gb |
|5452 |us |
+----------------------+-----------------+
-- Count the rows, subtotaled by Country
SELECT COUNT(*) AS TotalRowsbyCountry, Country
FROM Incidents
GROUP BY Country
ORDER BY Country DESC
+----------------------+-----------------+
|TotalRowsbyCountry | Country |
+----------------------+-----------------+
|5452 |us |
|1 |gb |
|249 |ca |
|750 |NULL |
+----------------------+-----------------+
SUM()은 열 값의 숫자 합계를 반환합니다
다른 집계 함수와 동일한 패턴을 따릅니다
GROUP BY와 함께 사용하면 지정한 열 기준으로 소계를 구할 수 있습니다
-- Calculate the values subtotaled by Country
SELECT SUM(DurationSeconds) AS TotalDuration, Country
FROM Incidents
GROUP BY Country
+----------+--------------------+
|Country |TotalDuration |
+----------+--------------------+
|us |17024946.750001565 |
|null |18859192.800000012 |
|ca |200975 |
|gb |120 |
+----------+--------------------+
중급 SQL Server