• 쇼핑몰
  • 커뮤니티
  • 북마크

MSSQL

The SQL GROUP BY syntax

아트스퀘어
2020.05.07 13:00 6,743 0

본문

he SQL GROUP BY syntax
The general syntax is:

  1. SELECT column-names
  2. FROM table-name
  3. WHERE condition
  4. GROUP BY column-names


The general syntax with ORDER BY is:

  1. SELECT column-names
  2. FROM table-name
  3. WHERE condition
  4. GROUP BY column-names
  5. ORDER BY column-names


 



SQL GROUP BY Examples



Problem: List the number of customers in each country
 

  1. SELECT COUNT(Id), Country
  2. FROM Customer
  3. GROUP BY Country



Results: 21 records.
 

CountCountry
3Argentina
2Austria
2Belgium
9Brazil
3Canada
ellipsis.png




Problem: List the number of customers in each country sorted high to low
 

  1. SELECT COUNT(Id), Country
  2. FROM Customer
  3. GROUP BY Country
  4. ORDER BY COUNT(Id) DESC



Results: 21 records.
 

CountCountry
13USA
11France
11Germany
9Brazil
7UK
ellipsis.png




Problem: List the total amount ordered for each customer
 

  1. SELECT SUM(O.TotalPrice), C.FirstName, C.LastName
  2. FROM [Order] O JOIN Customer C
  3. ON O.CustomerId = C.Id
  4. GROUP BY C.FirstName, C.LastName
  5. ORDER BY SUM(O.TotalPrice) DESC


This query uses a JOIN with Customer to obtain customer names

Results: 89 records.
 

SumFirstNameLastName
117483.39HorstKloss
115673.39JosePavarotti
113236.68RolandMendel
57317.39PatriciaMcKenna
52245.90PaulaWilson
34101.15MarioPontes
32555.55MariaLarsson
ellipsis.png

 

댓글목록 0

등록된 댓글이 없습니다.