W3. SQL Sum Flashcards
Q: What does the SQL SUM() function do?
A: It returns the total sum of a numeric column.
Q: Write a query to find the total quantity in the “Quantity” column of the “OrderDetails” table.
SELECT SUM(Quantity)
FROM OrderDetails;
Q: What is the syntax for using SUM() with a condition?
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Q: How can you use the WHERE clause with SUM()?
A: Add a WHERE clause to specify which rows to include in the sum calculation, e.g., WHERE ProductID = 11.
Q: Write a query to return the sum of “Quantity” for records with ProductID = 11.
SELECT SUM(Quantity) FROM OrderDetails WHERE ProductID = 11;
Q: How can you give a descriptive name to the result column of SUM()?
A: Use the AS keyword to set an alias, e.g., AS total.
Q: Write a query to find the total quantity and label it as “total.”
SELECT SUM(Quantity) AS total FROM OrderDetails;
Q: How do you use SUM() with GROUP BY?
A: Combine SUM() with GROUP BY to get the sum for each group, e.g., GROUP BY OrderID.
Q: Write a query to return the total quantity for each OrderID in “OrderDetails” and label it “Total Quantity.”
SELECT OrderID, SUM(Quantity) AS [Total Quantity] FROM OrderDetails GROUP BY OrderID;
Q: Can you use an expression inside the SUM() function?
A: Yes, e.g., SUM(Quantity * 10) to multiply each quantity by 10 before summing.
Q: Write a query that multiplies each quantity by 10 and then sums it in the “OrderDetails” table.
SELECT SUM(Quantity * 10) FROM OrderDetails;
Q: How can you join tables to calculate a sum with related data?
A: Use a JOIN to combine tables, then apply SUM() to calculate based on data from both tables.
Q: Write a query to find the total earnings by joining “OrderDetails” and “Products” to use actual prices.
SELECT SUM(Price * Quantity) FROM OrderDetails LEFT JOIN Products ON OrderDetails.ProductID = Products.ProductID;