Sum Data by Using A Query
Sum Data by Using A Query
This article explains how to use a type of function called an aggregate function to sum the data in a query result set. This article also briefly explains how to use other aggregate functions, such as COUNT and AVG to count or average the values in a result set. In addition, this article explains how to use the Total Row, a new feature in Microsoft Office Access 2007 that you use to sum data without having to alter the design of your queries. What do you want to do? Understand ways to sum data Prepare some sample data
Sum data by using a Total row Calculate group totals by using a totals query Sum data across multiple groups by using a crosstab query Aggregate function reference
Open your query in Datasheet view and add a Total row. The Total Row, a new feature in Office Access 2007, allows you to use an aggregate function in one or more columns of a query result set without having to change the design of your query. Create a totals query. A totals query calculates subtotals across groups of records; a Total row calculates grand totals for one or more columns (fields) of data. For example, if you want to subtotal all sales by city or by quarter, you use a totals query to group your records by the desired category and you then sum the sales figures. Create a crosstab query. A crosstab query is a special type of query that displays its results in a grid that resembles a Microsoft Office Excel 2007 worksheet. Crosstab queries summarize your values and then group them by two sets of facts one set down the side (row headings), and the other across the top (column headings). For example,
you can use a crosstab query to display sales totals for each city for the past three years, as the following table shows: City Paris Sydney Jakarta ... 2003 2004 2005 254,556 372,455 467,892 478,021 372,987 276,399 572,997 684,374 792,571 ... ... ...
Note The how-to sections in this document emphasize using the Sum function, but remember that you can use other aggregate functions in your Total rows and queries. For more information about using the other aggregate functions, see the section Aggregate function reference later in this article. For more information about ways to use the other aggregate functions, see the article Display column totals in a datasheet. The steps in the following sections explain how to add a Total row, use a totals query to sum data across groups, and how to use a crosstab query that subtotals data across groups and time intervals. As you proceed, remember that many of the aggregate functions work only on data in fields set to a specific data type. For example, the SUM function works only with fields set to the Number, Decimal, or Currency data types. For more information about the data types that each function requires, see the section Aggregate function reference, later in this article. For general information about data types, see the article Modify or change the data type set for a field. Top of Page
The how-to steps in this article use the following tables. Use these tables to create your sample data: The Categories table: Category Dolls Games and Puzzles Art and Framing Video Games DVDs and Movies Models and Hobbies Sports The Products table: Product Name Programmer action figure Fun with C# (A board game for the whole family) Relational Database Diagram The Magical Computer Chip (500 Pieces) Access! The Game! Computer Geeks and Mythical Creatures Exercise for Computer Geeks! The DVD! Ultimate Flying Pizza External 5.25-inch Floppy Diskette Drive (1/4 Scale) Bureaucrat non-action figure Gloom Build Your Own Keyboard The Orders table: Order Date Ship Date Ship City Shipping Fee 11/14/2005 11/15/2005 Jakarta $55.00 11/14/2005 11/15/2005 Sydney $76.00 11/16/2005 11/17/2005 Sydney $87.00 11/17/2005 11/18/2005 Jakarta $43.00 11/17/2005 11/18/2005 Paris $105.00 11/17/2005 11/18/2005 Stuttgart $112.00 11/18/2005 11/19/2005 Vienna $215.00 11/19/2005 11/20/2005 Miami $525.00 11/20/2005 11/21/2005 Vienna $198.00 11/20/2005 11/21/2005 Paris $187.00 Price Category $12.95 Dolls $15.85 Games and Puzzles $22.50 Art and Framing $32.65 Games and Puzzles $22.95 Games and Puzzles $78.50 Video Games $14.88 DVDs and Movies $36.75 Sports $65.00 Models and Hobbies $78.88 Dolls $53.33 Video Games $77.95 Models and Hobbies
11/21/2005 11/22/2005 Sydney 11/23/2005 11/24/2005 Jakarta The Order Details table: Order ID 1 1 2 2 2 3 4 4 5 6 7 7
$81.00 $92.00
Product Name Build Your Own Keyboard Bureaucrat non-action figure Exercise for Computer Geeks! The DVD! The Magical Computer Chip Computer Geeks and Mythical Creatures Access! The Game! Programmer Action Figure Ultimate Flying Pizza External 5.25-inch Floppy Diskette Drive (1/4 Scale) Relational Database Diagram Gloom Relational Database Diagram
Product ID 12 2 7 4 6 5 1 8 9 3 11 3
Unit Price $77.95 $78.88 $14.88 $32.65 $78.50 $22.95 $12.95 $36.75 $65.00 $22.50 $53.33 $22.50
Note Remember that in a typical database an order details table will contain only a Product ID field, not a Product Name field. The sample table uses a Product Name field to make the data easier to read. Enter the sample data manually 1. On the Create tab, in the Tables group, click Table. Access adds a new, blank table to your database. Note You do not need to follow this step if you open a new, blank database, but you will need to follow it whenever you need to add a table to the database. 2. Double-click the first cell in the header row and enter the name of the field in the sample table. By default, Access denotes blank fields in the header row with the text Add New Field, like so:
3. Use the arrow keys to move to the next blank header cell , and type the second field name (you can also press TAB or double-click the new cell). Repeat this step until you enter all field names.
4. Enter the data in the sample table. As you enter the data, Access infers a data type for each field. If you are new to relational databases, you should set a specific data type, such as Number, Text, or Date/Time, for each of the fields in your tables. Setting the data type helps ensure accurate data entry and also helps prevent mistakes, such as using a telephone number in a calculation. For these sample tables, you should let Access infer the data type. 5. When you finish entering the data, click Save. Keyboard shortcut Press CTRL+S. The Save As dialog box appears. 6. In the Table Name box, enter the name of the sample table, and then click OK. You use the name of each sample table because the queries in the how-to sections use those names. 7. Repeat these steps until you create each of the sample tables listed at the beginning of this section. If you do not want to enter the data manually, follow the next steps to copy the data to a spreadsheet file, and then import the data from the spreadsheet file into Access. Create the sample worksheets 1. Start your spreadsheet program and create a new, blank file. If you use Excel, it creates a new, blank workbook by default. 2. Copy the first sample table provided above and paste it into the first worksheet, starting at the first cell. 3. Using the technique provided by your spreadsheet program, rename the worksheet. Give the worksheet the same name as the sample table. For example, if the sample table is named Categories, give your worksheet the same name. 4. Repeat steps 2 and 3, copying each sample table to a blank worksheet and renaming the worksheet. Note You might need to add worksheets to your spreadsheet file. For information on doing that task, see the help for your spreadsheet program. 5. Save the workbook to a convenient location on your computer or your network, and go to the next set of steps. Create database tables from the worksheets
1. On the External Data tab, in the Import group, click Excel. -orClick More, and then select a spreadsheet program from the list. The Get External Data - Program Name Spreadsheet dialog box appears. 2. Click Browse, open the spreadsheet file that you created in the previous steps, and then click OK. The Import Spreadsheet Wizard starts. 3. By default, the wizard selects the first worksheet in the workbook (the Customers worksheet, if you followed the steps in the previous section), and data from the worksheet appears in the lower section of the wizard page. Click Next. 4. On the next page of the wizard, click First row contains column headings, and then click Next. 5. Optionally, on the next page, use the text boxes and lists under Field Options to change field names and data types or to omit fields from the import operation. Otherwise, click Next. 6. Leave the Let Access add primary key option selected, and click Next. 7. By default, Access applies the name of the worksheet to your new table. Accept the name or enter another name, and then click Finish. 8. Repeats steps 1 through 7 until you have created a table from each worksheet in the workbook. Rename the primary key fields Note When you imported the worksheets, Access automatically added a primary key column to each table and, by default, Access named that column "ID" and set it to the AutoNumber data type. The steps in this explain how to rename each primary key field. Doing so helps to clearly identify all the fields in a query. 1. In the Navigation Pane, right-click each of the tables that you created in the previous steps and click Design View. 2. For each table, locate the primary key field. By default, Access names each field ID. 3. In the Field Name column for each primary key field, add the name of the table. For example, you would rename the ID field for the Categories table to "Category ID" and the field for the Orders table to "Order ID." For the Order Details table, rename the field to "Detail ID." For the Products table, rename the field to "Product ID."
4. Save your changes. Whenever the sample tables appear in this article, they include the primary key field, and the field is renamed as described by using the preceding steps. Top of Page
The query result set appears in Datasheet view. 5. Optionally, switch to Design view and adjust your query. To do so, right-click the document tab for the query and click Design View. You can then adjust the query, as needed, by adding or removing table fields. To remove a field, select the column in the design grid and press DELETE. 6. Save your query. Add a Total row 1. Make sure that your query is open in Datasheet view. To do so, right-click the document tab for the query and click Datasheet View.
-orIn the Navigation Pane, double-click the query. This runs the query and loads the results into a datasheet. 2. On the Home tab, in the Records group, click Totals. A new Total row appears in your datasheet. 3. In the Total row, click the cell in the field that you want to sum, and then select Sum from the list. Hide a Total row
For more information about using a Total row, see the article Display column totals in a datasheet. Top of Page
A simple grand total that sums the values in a single column. For example, you can calculate total shipping costs. A calculated grand total that sums the values in more than one column. For example, you can calculate total sales by multiplying the cost of several items by the number of item ordered, and then totaling the resulting values. A grand total that excludes some records. For example, you can calculate the total sales only for last Friday.
The steps in the following sections explain how to create each type of grand total. The steps use the Orders and Order Details tables. The Orders table Order ID Order Date Ship Date Ship City Shipping Fee 1 11/14/2005 11/15/2005 Jakarta $55.00 2 11/14/2005 11/15/2005 Sydney $76.00 3 11/16/2005 11/17/2005 Sydney $87.00 4 11/17/2005 11/18/2005 Jakarta $43.00
5 6 7 8 9 10 11 12
11/18/2005 Paris 11/18/2005 Stuttgart 11/19/2005 Vienna 11/20/2005 Miami 11/21/2005 Vienna 11/21/2005 Paris 11/22/2005 Sydney 11/24/2005 Jakarta
The Order Details table Detail ID 1 2 3 4 5 6 7 8 9 10 11 12 Order Product Name ID 1 Build Your Own Keyboard 1 Bureaucrat non-action figure Exercise for Computer Geeks! The 2 DVD! 2 The Magical Computer Chip Computer Geeks and Mythical 2 Creatures 3 Access! The Game! 4 Programmer Action Figure 4 Ultimate Flying Pizza External 5.25-inch Floppy Diskette 5 Drive (1/4 Scale) 6 Relational Database Diagram 7 Gloom 7 Relational Database Diagram Product Unit Quantity Discount ID Price 12 $77.95 9 0.05 2 $78.88 4 0.075 7 4 6 5 1 8 9 3 11 3 $14.88 $32.65 $78.50 $22.95 $12.95 $36.75 $65.00 $22.50 $53.33 $22.50 6 8 4 5 2 8 4 12 6 4 0.04 0.00 0.00 0.15 0.06 0.04 0.10 0.065 0.08 0.09
Calculate a simple grand total 1. On the Create tab, in the Other group, click Query Design. 2. In the Show Table dialog box, double-click the table that you want to use in your query, and then click Close. If you use the sample data, double-click the Orders table. The table appears in a window in the upper section of the query designer. 3. Double-click the field that you want to sum. Make sure that the field is set to either the Number or Currency data type. If you try to sum values in non-numeric fields, such as a Text field, Access displays the Data type mismatch in criteria expression error message when you try to run the query.
If you use the sample data, double-click the Shipping Fee column. Note You can add additional numeric fields to the grid if you want to calculate grand totals for those fields. A totals query can calculate grand totals for more than one column. 4. On the Design tab, in the Show/Hide group, click Totals. The Total row appears in the design grid and Group By appears in the cell in the Shipping Fee column. 5. Change the value in the cell in the Total row to Sum. 6. Click Run to run the query and display the results in Datasheet view. Tip Note that Access appends "SumOf" to the beginning of the name of the field that you sum. To change the column heading to something more meaningful, such as Total Shipping, switch back to Design view, and click in the Field row of the Shipping Fee column in the design grid. Place the cursor next to Shipping Fee and type the words Total Shipping, followed by a colon, like so: Total Shipping: Shipping Fee. 7. Optionally, save the query and close it. Calculate a grand total that excludes some records 1. On the Create tab, in the Other group, click Query Design. 2. In the Show Table dialog box, double-click the Order table and Order Details table, and then click Close to close the dialog box. 3. Add the Order Date field from the Orders table to the first column in the query design grid. 4. In the Criteria row of the first column, type Date() -1. That expression excludes the current day's records from the calculated total. 5. Next, create the column that calculates the sales amount for each transaction. Type the following expression in the Field row of the second column in the grid: Total Sales Value: (1-[Order Details].[Discount]/100)*([Order Details].[Unit Price]*[Order Details].[Quantity]) Make sure your expression references fields set to the Number or Currency data types. If your expression refers to fields set to other data types, Access displays the message Data type mismatch in criteria expression when you try to run the query. 6. On the Design tab, in the Show/Hide group, click Totals. The Total row appears in the design grid and Group By appears in the first and second columns.
7. In the second column, change the value in the cell of the Total row to Sum. The Sum function adds the individual sales figures. 8. Click Run to run the query and display the results in Datasheet view. 9. Save the query as Daily Sales. Note The next time that you open the query in Design view, you might notice a slight change in the values specified in the Field and Total rows of the Total Sales Value column. The expression appears enclosed inside the Sum function, and the Total row displays Expression instead of Sum. For example, if you use the sample data and create the query (as shown in the previous steps), you see: Total Sales Value: Sum((1-[Order Details].Discount/100)*([Order Details].Unitprice*[Order Details].Quantity)) Top of Page
11 12
The Order Details table Detail ID 1 2 3 4 5 6 7 8 9 10 11 12 Order Product Name ID 1 Build Your Own Keyboard 1 Bureaucrat non-action figure Exercise for Computer Geeks! The 2 DVD! 2 The Magical Computer Chip Computer Geeks and Mythical 2 Creatures 3 Access! The Game! 4 Programmer Action Figure 4 Ultimate Flying Pizza External 5.25-inch Floppy Diskette 5 Drive (1/4 Scale) 6 Relational Database Diagram 7 Gloom 7 Relational Database Diagram Product Unit Quantity Discount ID Price 12 $77.95 9 5% 2 $78.88 4 7.5% 7 4 6 5 1 8 9 3 11 3 $14.88 $32.65 $78.50 $22.95 $12.95 $36.75 $65.00 $22.50 $53.33 $22.50 6 8 4 5 2 8 4 12 6 4 4% 0 0 15% 6% 4% 10% 6.5% 8% 9%
The following steps assume a one-to-many relationship between the Product ID fields in the Orders table and Order Details table, with the Orders table on the "one" side of the relationship. Create the totals query 1. On the Create tab, in the Other group, click Query Design. 2. In the Show Table dialog box, select the tables that you want to work with, click Add, and then click Close after you have finished adding the tables. -orDouble-click the tables that you want to use, and then click Close. Each table appears as a window in the upper section of the query designer. If you use the sample tables listed previously, you add the Products and Order Details tables. 3. Double-click the table fields that you want to use in your query. As a rule, you add only the group field and the value field to the query. However, you can use a calculation instead of a value field the next steps explain how to do so.
1. Add the Category field from the Products table to the design grid. 2. Create the column that calculates the sales amount for each transaction by typing the following expression in the second column in the grid: Total Sales Value: (1-[Order Details].[Discount]/100)*([Order Details].[Unit Price]*[Order Details].[Quantity]) Make sure that the fields that you reference in the expression are of the Number or Currency data types. If you reference fields of other data types, Access displays the error message Data type mismatch in criteria expression when you try to switch to Datasheet view. 3. On the Design tab, in the Show/Hide group, click Totals. The Total row appears in the design grid, and in that row, Group By appears in the first and second columns. 4. In the second column, change the value in the Total row to Sum. The Sum function adds the individual sales figures. 5. Click Run to run the query and display the results in Datasheet view. 6. Keep the query open for use in the next section.
Criteria that ignore certain groups when calculating totals. For example, you will calculate totals for just the Video Games, Art and Framing, and Sports categories. Criteria that hide certain totals after calculating them. For example, you can display only the totals greater than $150,000. Criteria that exclude individual records from being included in the total. For example, you can exclude individual sales transactions when the value (Unit Price * Quantity) drops below $100.
The following steps explain how to add the criteria one by one and see the impact on the query result. Add criteria to the query
1. Open the query from the previous section in Design view. To do so, right-click the document tab for the query and click Design View. -orIn the Navigation Pane, right-click the query and click Design View. 2. In the Criteria row of the Category ID column, type =Dolls Or Sports or Art and Framing. 3. Click Run to run the query and display the results in Datasheet view. 4. Switch back to Design view and, in the Criteria row of the Total Sales Value column, type >100. 5. Run the query to see the results, and then switch back to Design view. 6. Now add the criteria to exclude individual sales transactions that are less than $100. To do this, you need to add another column. Note You cannot specify the third criteria in the Total Sales Value column. Any criteria that you specify in this column applies to the total value, not to the individual values. 7. Copy the expression from the second column to the third column. 8. In the Total row for the new column, select Where and, in the Criteria row, type >20. 9. Run the query to see the results, and then save the query. Note The next time you open the query in Design view, you might notice slight changes in the design grid. In the second column, the expression in the Field row will appear enclosed inside the Sum function, and the value in the Total row displays Expression instead of Sum. Total Sales Value: Sum((1-[Order Details].Discount/100)*([Order Details].Unitprice*[Order Details].Quantity)) You will also see a fourth column. This column is a copy of the second column, but the criteria that you specified in the second column actually appears as part of the new column. Top of Page
As you proceed, remember that a crosstab query does not always populate all the fields in the result set because the tables that you use in the query do not always contain values for every possible data point. When you create a crosstab query, you typically include data from more than one table, and you always include three types of data: the data used as row headings, the data used as column headings, and the values that you want to sum or otherwise compute. The steps in this section assume the following tables: The Orders table Order Date Ship Date Ship City Shipping Fee 11/14/2005 11/15/2005 Jakarta $55.00 11/14/2005 11/15/2005 Sydney $76.00 11/16/2005 11/17/2005 Sydney $87.00 11/17/2005 11/18/2005 Jakarta $43.00 11/17/2005 11/18/2005 Paris $105.00 11/17/2005 11/18/2005 Stuttgart $112.00 11/18/2005 11/19/2005 Vienna $215.00 11/19/2005 11/20/2005 Miami $525.00 11/20/2005 11/21/2005 Vienna $198.00 11/20/2005 11/21/2005 Paris $187.00 11/21/2005 11/22/2005 Sydney $81.00 11/23/2005 11/24/2005 Jakarta $92.00 The Order Details table Order ID 1 1 2 2 Product Name Build Your Own Keyboard Bureaucrat non-action figure Exercise for Computer Geeks! The DVD! The Magical Computer Chip Product ID 12 2 7 4 Unit Price $77.95 $78.88 $14.88 $32.65 Quantity Discount 9 4 6 8 5% 7.5% 4% 0
2 3 4 4 5 6 7 7
Computer Geeks and Mythical Creatures Access! The Game! Programmer Action Figure Ultimate Flying Pizza External 5.25-inch Floppy Diskette Drive (1/4 Scale) Relational Database Diagram Gloom Relational Database Diagram
6 5 1 8 9 3 11 3
4 5 2 8 4 12 6 4
The following steps explain how to create a crosstab query that groups total sales by city. The query uses two expressions to return a formatted date and a sales total. Create a crosstab query 1. On the Create tab, in the Other group, click Query Design. 2. In the Show Tables dialog box, double-click the tables that you want to use in your query, and then click Close. Each table appears as a window in the upper section of the query designer. If you use the sample tables, double-click the Orders table and the Order Details table. 3. Double-click the fields that you want to use in your query. Each field name appears in the a blank cell in the Field row of the design grid. If you use the sample tables, add the Ship City and Ship Date fields from the Orders table. 4. In the next blank cell in the Field row, copy and paste or type the following expression: Total Sales: Sum(CCur([Order Details].[Unit Price]*[Quantity]*(1[Discount])/100)*100) 5. On the Design tab, in the Query Type group, click Crosstab. The Total row and the Crosstab row appear in the design grid. 6. Click the cell in the Total row in the City field and select Group By. Do the same for the Ship Date field. Change the value in the Total cell of the Total Sales field to Expression. 7. In the Crosstab row, set the cell in the City field to Row Heading, set the Ship Date field to Column Heading, and set the Total Sales field to Value. 8. On the Design tab, in the Results group, click Run. The query results appear in Datasheet view.
Top of Page
Count
Returns the item with the highest value. For text data, the highest value is the last Maximum Number, Currency, Date/Time alphabetic value Access ignores case. The function ignores null values. Returns the item with the lowest value. For text data, the lowest value is the first Minimum Number, Currency, Date/Time alphabetic value Access ignores case. The function ignores null values. Measures how widely values are dispersed from an average value (a mean). Standard Number, Currency Deviation For more information about using this function, see the article Display column totals in a datasheet. Adds the items in a column. Works only on Sum Number, Currency numeric and currency data. Variance Measures the statistical variance of all values Number, Currency in the column. You can use this function only on numeric and currency data. If the table contains less than two rows, Access
returns a null value. For more information about variance functions, see the article Display column totals in a datasheet.