W3. SQL Group By Flashcards
Q: What does the SQL GROUP BY statement do?
A: It groups rows that have the same values into summary rows, often used with aggregate functions.
Q: When is the GROUP BY statement commonly used?
A: It’s used with aggregate functions like COUNT(), MAX(), MIN(), SUM(), and AVG() to group results by one or more columns.
Q: Write the syntax for a GROUP BY statement.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Q: Write a query to count the number of customers in each country.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
Q: How do you sort a GROUP BY result in descending order by count?
A: Use ORDER BY COUNT(column_name) DESC.
Q: Write a query to list the number of customers in each country, sorted high to low.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
Q: Can you use GROUP BY with JOIN statements?
A: Yes, GROUP BY can be used with JOIN to group results based on related data from multiple tables.
Q: Write a query to list the number of orders sent by each shipper.
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;