The SQL GROUP BY syntax
아트스퀘어
2020.05.07 13:00
20,059
0
-
9833회 연결
-
0회 연결
본문
he SQL GROUP BY syntax
The general syntax is:
- SELECT column-names
- FROM table-name
- WHERE condition
- GROUP BY column-names
The general syntax with ORDER BY is:
- SELECT column-names
- FROM table-name
- WHERE condition
- GROUP BY column-names
- ORDER BY column-names
SQL GROUP BY Examples
Problem: List the number of customers in each country
- SELECT COUNT(Id), Country
- FROM Customer
- GROUP BY Country
Results: 21 records.
| Count | Country |
|---|---|
| 3 | Argentina |
| 2 | Austria |
| 2 | Belgium |
| 9 | Brazil |
| 3 | Canada |
![]() | |
Problem: List the number of customers in each country sorted high to low
- SELECT COUNT(Id), Country
- FROM Customer
- GROUP BY Country
- ORDER BY COUNT(Id) DESC
Results: 21 records.
| Count | Country |
|---|---|
| 13 | USA |
| 11 | France |
| 11 | Germany |
| 9 | Brazil |
| 7 | UK |
![]() | |
Problem: List the total amount ordered for each customer
- SELECT SUM(O.TotalPrice), C.FirstName, C.LastName
- FROM [Order] O JOIN Customer C
- ON O.CustomerId = C.Id
- GROUP BY C.FirstName, C.LastName
- ORDER BY SUM(O.TotalPrice) DESC
This query uses a JOIN with Customer to obtain customer names
Results: 89 records.
| Sum | FirstName | LastName |
|---|---|---|
| 117483.39 | Horst | Kloss |
| 115673.39 | Jose | Pavarotti |
| 113236.68 | Roland | Mendel |
| 57317.39 | Patricia | McKenna |
| 52245.90 | Paula | Wilson |
| 34101.15 | Mario | Pontes |
| 32555.55 | Maria | Larsson |
![]() | ||

댓글목록 0