The COMPUTE BY Clause
As you recall from Chapter 20, SQL SELECT statements return a set of rows, all of whichhave the same structure. In other words, a SQL query can return either details or totals, but notboth. For example, you can calculate the order totals for all customers with a GROUP BY clause,but this clause displays totals only. Let’s say you want a list of all customers in the Northwind data-base, their orders, and the total for each customer. Listing 1 provides a SQL SELECT statementthat retrieves the desired information from the database.
Listing 1: The OrderTotals.sql Query
USE NORTHWINDSELECT CompanyName, Orders.OrderID,SUM([Order Details].UnitPrice * Quantity * (1 - Discount))FROM Products, [Order Details], Customers, OrdersWHERE [Order Details].ProductID = Products.ProductID AND[Order Details].OrderID = Orders.OrderID ANDOrders.CustomerID=Customers.CustomerIDGROUP BY CompanyName, Orders.OrderIDORDER BY CompanyName, Orders.OrderID
This statement calculates the totals for each order. The
Orders.OrderID
field is included in theGROUP BY clause because it’s part of the SELECT list, but doesn’t appear in an aggregate func-tion’s arguments. This statement will display groups of customers and the totals for all orders placedby each customer:
Alfreds Futterkiste 10643 814.5Alfreds Futterkiste 10692 878.0Alfreds Futterkiste 10702 330.0Alfreds Futterkiste 10835 845.80Alfreds Futterkiste 10952 471.20Alfreds Futterkiste 11011 933.5Ana Trujillo Emparedados y helados 10308 88.80Ana Trujillo Emparedados y helados 10625 479.75. . .
If you want to see the totals per customer, you must modify Listing 1 as follows:
USE NORTHWINDSELECT CompanyName,SUM([Order Details].UnitPrice * Quantity * (1 - Discount))FROM Products, [Order Details], Customers, OrdersWHERE [Order Details].ProductID = Products.ProductID AND[Order Details].OrderID = Orders.OrderID ANDOrders.CustomerID=Customers.CustomerIDGROUP BY CompanyNameORDER BY CompanyName
Bonus Reference
TRANSACT-SQL
chT2
Leave a Comment
Thanks