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 ใช้ร่วมกับ COUNT() ได้เช่นเดียวกับฟังก์ชัน Aggregation อื่น ๆ เช่น AVG(), MIN(), MAX()
ใช้คำสั่ง 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() คืนค่าผลรวมของตัวเลขในคอลัมน์
ใช้รูปแบบเดียวกับฟังก์ชัน Aggregation อื่น ๆ
ใช้ร่วมกับ 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 ระดับกลาง