Data Science Explorer

[Basic Grammar] SQL Sum 본문

SQL

[Basic Grammar] SQL Sum

grace21110 2023. 10. 15. 11:21
반응형

The SUM () function gives you the totla sum of a numeric column. 

  • Syntax 
SELECT SUM(column_name)
FROM table_name
WHERE condition;

Example 

Write an SQL query to return the sum of all the "TotalAmount" fields in the "Invoices" table.

SELECT SUM(TotalAmount) AS "Total Sum"
FROM Invoices;

 

  • Add a WHERE Clause

This is to specify conditions: 

Example 

Return the number of orders made for the product with CustomerID: 18000

SELECT SUM (Quantity) 
FROM OrderDeatils
WHERE CustomerID: 18000;

 

  • Use an Alias 

Example 

Name the column "country":

SELECT SUM (Quantity) AS country 
FROM OrderDetails;

 

  • SUM() with an Expression

This function can also be used as an expression. 

Example 

SELECT SUM(Quantity * 10)
FROM OrderDetails;

 

Exercises 

1. Use an SQL function to calculate the sum of all the "OrderTotal" values in the "Orders" table.

SELECT SUM(Salary)
FROM Employees;

 

 

 

2. Write an SQL query to calculate the total earnings as the sum of the "Sales" and "Bonus" columns in the "SalesTeam" table for each salesperson.

SELECT SUM(Sales + Bonus) AS "Total Earnings"
FROM SalesTeam 
GROUP BY Salesperson;

'SQL' 카테고리의 다른 글

[Basic Grammar] SQL LIKE Operator  (0) 2023.10.16
[Basic Grammar] SQL AVG() Function  (0) 2023.10.15
[Basic Grammar] SQL COUNT Function  (0) 2023.10.14
[Basic Grammar] SQL MIN() and MAX() Functions  (0) 2023.10.14
[Basic Grammar] SQL DELETE Statement  (0) 2023.10.14