Sie sind auf Seite 1von 47

|

Home

Excel

Access

Word

Outlook

FrontPage

VBA

Downloads

Index

Query Criteria...

Access Query and Filter Criteria

Access Index

When constructing a query or a filter, you need to tell Access what to look for i field. You do this by defining criteria - typing something (an "expression") into

Printer friendly version

cell of the query or filter grid. If you do not define any criteria for a particular f

assumes that you are applying no constraints and will display everything it has. This means that you only have to define c those fields you are interested in.

Here are some examples of the more common types of criteria. Often Access will complete the expression so that you nee

the text you want to match. However, sometimes Access has a choice so you should always check that what Access has w same as you intended. If what you type doesn't make sense to Access, you will see an error message.

The list of examples below is not exhaustive. Try using combinations of different expressions and see what you get. Also,

immediately assume that you have made a mistake if you get no records when you run the query or filter. It means that A

find anything to match your criteria. That may be because you've asked for something impossible, but it could equally me criteria were perfectly OK but there simply aren't any matching records.

This tutorial is arranged in the following sections:

Matching Text

Using Wildcards

Working with Numbers

Working with Dates

Excluding Things

Finding Empty Fields

Matching Text

When you enter text into the criteria cell your text should be enclosed in quotes ("") to distinguish it from other expression operators that you may need to add.

"Text"

To match a word or phrase simply type the text you want to match. The query will find all the records that match the text

Access will add the quote marks at each end. It is only necessary to enter the quotes yourself if you type text that might c

query. For example you may want to type a phrase that contains the words "and" or "or". Access would normally interpret

words as instructions. You can manually insert the quote marks at ea

the phrase to make sure the criterion means what you intend it to. T

will display all the records that contain the entry London in the Town

"Text" Or "Text"

To match one of two or more words or phrases, type the text you want to match separated by the word "or". The query w

the records that match any of the words or phrases. Enter quote marks yourself if you think the text might confuse the qu example will display all the records that contain either London or Paris in the Town field.

"Text" "Text"

To match one of several words or phrases, you can type each word or phrase in a new row moving down the column. This

same result as using "or" but has the advantage that your criteria might be easier to read. This example will display all th

that contain the entry London, Paris or Amsterdam in the Town field. Note: If this method is combined with criteria for oth those criteria must be repeated for each row.

In ("Text", "Text", "Text")

To match a word or phrase from a list, type the list items separated by commas, and enclose the list in round brackets (pa

Access will add the expression "In" and place quote marks where needed - you can do this manually if you wish. This exam display all the records that contain UK or USA or France in the Country field.

Not "Text"

To exclude a word or phrase, use the expression "Not" followed by the word of phrase you want to exclude (enclosed in q example will display records that contain anything other than London in the Town field.

Not In ("Text", "Text", "Text")

To exclude a list of words or phrases from the search use the same method as for matching from a list but add the expres

at the beginning. This example will display all records that contain anything other than UK or USA or France in the Country

Using Wildcards

A wildcard is a special character that can stand for either a single character or a string of text. Wildcards are useful when

the query to look for a range of different possible values, and also when you are not certain exactly what you are looking f give the query some clues to work with.

The two wildcards we commonly use are the asterisk or star (*) and the ques

(?).The asterisk (*) represents any string of text from nothing up to an entire

or more. The question mark (?) represents a single character only (although y use, for example, two question marks to represent two unknown characters).

For example:

Yor* would find York, Yorkshire and Yorktown but not New York.

Mar? would find Mark but not Mario, Martin or Omar.

F*d would find Fred and Ferdinand but not Frederick.

Like "Text*" To match text starting with a particular letter or string type the letter or string of text followed by an asterisk. Access will

expression "Like" and place quotes around your typing. This example will display all records that have an entry starting w Company field.

Like "*Text"

To match text ending with a particular letter or string type an asterisk followed by a letter or string of text. This example w all records that have an entry ending with Plc in the Company field.

Like "[Letter-Letter]*"

To match text starting with letters within a certain range you must type the entire expression as shown (this one is too co for Access to work out what you want. This example will display all the records with entries starting with the letters A - D Company field.

You can often get the same results by using mathematical operators such as greater than (>) and less than (<). These ar used for specifying numbers and dates but can also be used for text.

For example:

<"N" would find all entries beginning with a letter lower than the letter N in the alphabet. In other words, all e

starting with the letters A - M. >"F" And <"H" would find all entries beginning with the letters F and G.

Working with Numbers

When working with numbers we normally use the mathematical operators to define the range of numbers from which we w select.

For example, where X represents a number:

<X finds values less than X.

>X finds vales greater than X

>=X finds values greater than or equal to X

<>X finds vales not equal to X

It is important that your field type is correctly defined as a Number field for numerical queries to work properly. Here are s examples

To match a number simply type the number that you want the query to find. This example will display the record(s) with t 385 in the CustomerNumber field.

<X

To find values less than a certain number type a less than sign (<) followed by the number. This example will display all re an entry less than 1000 in the CustomerNumber field.

Between X And Y

To find values in a range of numbers type the expression shown where X and Y represent the numbers at opposite ends of This example will display all records with entries falling within the range 500-700 in the CustomerNumber field.

Working with Dates

Dates behave the same way as numbers, so you can use some of the same techniques when constructing your date query

Remember, for dates to be treated properly by Access it is import your field type has been correctly defined as a Date/Time field. It

matter how you enter the date, as long as you use a recognised fo

date will be displayed in the resulting dynaset in whatever format when you created the table.

When you enter a date in the criteria cell you can use any standard date format, but each date must be enclosed by hash

For example:

<#1/1/98# finds dates earlier than 1 January 1998

=#27-Sep-50# finds dates equal to 27 September 1950

Between #5/7/98# And #10/7/98# finds dates no earlier than 5 July 1998 and no later than 10 July 199

Here are some more examples

=#Date#

To match a particular date type the date enclosed by hash marks (#). This example will display all the records with entries September 1998 in the Invoice Date field.

=Date()

To match today's date type the expression shown. Date() means "today". This example will display all the records with en the current date in the Invoice Date field.

Year([Fieldname])=Year(Now())

To match the current year type the expression shown, entering the name of the current field in square brackets where ind example will display all the records with entries for the current year in the Invoice Date field.

Year([Fieldname])=Year

To match a particular year type the expression shown, entering the name of the current field in square brackets where ind the required year in place of Year. This example will display all the records with a date in 1998 in the Invoice Date field.

<Date()-30

To match a particular calculated date range you will need to use a combination

expressions. This expression employs a calculation that subtracts 30 fr

current date and also includes the less than operator. This example wi

the records with a date more than 30 days old in the Invoice Date field

Excluding Things

Sometimes you want to specifically exclude criteria from your search. This is done with the expression Not. This expressio used on its own or in combination with other expressions.

For example:

Not "text" finds all records except those matching the specified text.

Not Like "X*" finds all records except those starting with the specified letter (or string of text).

Here are some more examples:

Not "Text"

To exclude specific records from the search use the expression Not followed by the text which matches those records you

out. The text needs to be between quotes as shown here - Access will normally do that for you. This example will find all r contacts in towns other than London.

Not Like "Text*"

You can use wildcards with the Not expression, which then becomes Not Like followed by your wildcard criteria. Here is j example. This example will find all records for contacts in towns starting will letters other than L.

And Not "Text"

The Not expression can be used in combination with other expressions, when it becomes And Not followed by the text yo

exclude from your search. This example will find all records for contacts in towns starting with the letter L but will exclude London.

Finding Empty Fields

A query can be used to find records where specific fields are empty. To do thi

the expression Is Null. Conversely, to find records for which specific fields ar

you use the expression Is Not Null. The expression Null simply means "noth

If you have made use of the "allow zero length" field property you can search

length entries. Sometimes you want to distinguish between, for example, rec

which you don't happen to have the particular piece of information for a certain field and those for which you know there d isn't any information available. Is the Fax Number field empty because you don't know the person's fax number or is it be don't have a fax? Either way you can't type a fax number into the field. It has to be left empty. Well, not exactly

You can make a "zero length entry" (providing this feature has been enabled in the properties of the field - in the table's d view). To do this when entering data type two double-quote marks together without a space between, like this "". When the field the quote marks disappear and the field looks just like any other empty field - except Access knows it contains a

entry. You can search for zero length entries with a query. It is important to remember that if you make use of zero length

Null will not find them. It regards them as a piece of text and therefore a field containing a zero length entry is not empty doesn't contain any data. Confused? Read it again then try it out - it does make sense eventually!

Here are some examples:

Is Null

To find empty fields use the Is Null expression. This looks for fields that contain no data. This example will find all records contacts whose fax number has not been recorded.

Is Not Null

To find fields that are not empty use the Is Not Null expression. This looks for fields that contain data. If there is someth

field the record will be shown. Note that Is Not Null will find fields containing zero length entries. (If you want to leave th

excluding them with the And Not expression.) This example finds all records for contacts whose fax number has been rec

""

To find zero length entries use "" expression. This looks for zero length entries in the specified field. This example would f depending on why you had made use of the zero length entry feature, all records for contacts who did not have a fax.

As I said at the beginning, this is not an exhaustive list of query criteria. Many of these expressions can be combined to cr

complex criteria. You can use calculations to construct criteria. The scope is almost limitless. Use your imagination and see

get! Above all, remember that Access is logical. If you don't get the result you were expecting, read the grid a line at a tim

what Access does) and see if it makes sense. Sometimes it helps to go and check out the SQL (the language Access uses t

query - SQL stands for Structured Query Language). You can view the SQL by clicking the SQL View button on the toolba

Sign in | Romnia - Romn | H ome Libra ry Lear n | Dow nloa ds Sup port Com mun ity

MSDN Library

Office Development

2007 Microsoft Office System

Access 2007

Technical Articles

Basics for Building Access 2007 Runtime-Based Solutions

Building SQL Statements that Include Variables and Controls in Access 2007

Constructing Modern Time Elapsed Strings in Access 2007

Counting the Number of Working Days in Access 2007

Creating Managed Add-ins for Access 2007

Customizing the Office Fluent User Interface in Access 2007

Deploying Access 2007 Runtime-Based Solutions

Developing Access 2007 Solutions with Native C or C++

Developer Considerations for Choosing File Formats in Access 2007

Error Handling and Debugging Tips for Access 2007, VB, and VBA

Integrating Workflows into Access 2007 Applications

Performance Tips to Speed Up Your Access 2007 Database

Security Considerations and Guidance for Access 2007

Tips and Techniques for Queries in Access 2007

Transitioning Your Existing Access Applications to Access 2007

Using Excel Date Functions in Access 2007

Using SQL Server 2008 Table-valued Parameters in Access 2007 Community Content

Microsoft Access Append versus M... We added a new paper to our Micr...


More...

Microsoft Access Query Help Cent... We've created a consolidated cen...

Tips and Techniques for Queries in Access 2007


Office 2007 Summary: Learn about queries and their uses in Microsoft Office Access 2007. (29 printed pages) Luke Chung, President of FMS Inc August 2009 Apples to: 2007 Microsoft Office System, Microsoft Office Access 2007 Contents

Overview Query Types Basic Select Queries Setting Criteria Advanced Select Queries Action Queries Queries in Forms, Reports, and Macros Running Queries through Macros Using and Running Queries in VBA Code Additional Resources from Microsoft

About the Author Additional Resources from FMS, Inc.


Download the Sample Access Database

Overview
Microsoft Office Access 2007 is the most popular Windows database program. A major reason for its success is its revolutionary query interface. Once data is collected in a database, analysis and updates need to be performed. Queries offer the ability to retrieve and filter data, calculate summaries (totals), and update, move and delete records in bulk. Mastering Microsoft Access queries will improve your ability to manage and understand your data and simplify application development. The visual representation of tables and the graphical links between them makes Microsoft Access queries extremely easy to use. Fortunately, the nice user interface also allows very powerful and advanced analysis. The entire query engine is modeled on SQL systems and allows switching between the graphical query design and SQL syntax. Many Microsoft Access users and developers learned SQL from this feature. Knowing the many features of Microsoft Access queries allows you to perform advanced analysis quickly without programming. This presentation covers the basics of queries revealing a variety of subtleties. It quickly moves to more advanced topics with hints and techniques for creating sophisticated queries. Finally, programmatic use of queries is presented.

Query Types
Microsoft Access supports many types of queries. Here is a description of the major categories:

Select Queries
Retrieve records or summaries (totals) across records. Also includes cross-tabulations.

Make Table Queries


Similar to Select Queries but results are placed in a new table.

Append Queries
Similar to Select Queries but results are added to an existing table

Update Queries
Modify data in the records.

Delete Queries
Records are deleted from a table. Select queries are the most common queries and can be used for viewing and a data source for forms, reports, controls, and other queries. The other queries create or change data and are known collectively as Action queries.

Basic Select Queries


The most basic Select queries retrieve the records you specify from a table. You can choose the fields from a table to display, and specify the criteria for selecting records. In the most cases, while viewing the query results you can modify the data and update the original records. These updateable views are extremely powerful. Selecting Tables and Fields The first step in creating a query is to specify the table or tables to use and the fields to display. Selecting tables is simple. Just choose the table from the list when the query is first created or use the Add Table command from the Query menu. The selected table is placed on the upper portion of the query design window. From there you can select the fields for the query by double-clicking on them or selecting several fields (by using Shift-Click or Ctrl-Click) and dragging them to the bottom portion of the query by example (QBE) grid. Make sure that the Show option is checked to display the field. Sorting and Reordering Fields Once you place the fields on the QBE grid, you can reorder the fields by clicking the column and dragging it to where you want it. To sort the results, specify the Sort option under the fields to sort. You can choose Ascending or Descending order. Note that you can turn off the Show setting and sort on a field that does not appear in the display. Renaming Fields A very nice feature of Microsoft Access queries is the ability to rename fields. You might have your data stored in field names that users do not understand. By using a query expression, you can change the field name the user sees. For example, you can change a field named

CustID to Customer ID by placing the new name followed by a colon and the original name
in the QBE field cell: Customer ID:[CustID]. Using Calculated Fields (Expressions) In addition to retrieving fields from a table, a Select query can also display calculations (expressions). Of course, expressions cannot be updated because they do not exist in the original table. Expressions are extremely powerful and allow you to easily display complex calculations. There is an Expression Builder that simplifies the selection of fields and functions.

By default, expression fields are named Expr1, Expr2, and so on; therefore, you usually want to rename them to something more understandable. Setting Query Properties When you design a query, you can choose View | Properties or right click the top portion of the query and then choose Properties to see and modify the query properties.

Figure 1. Query properties

Description This property lets you provide a description of the query. Use the property to help you remember the purpose of the query. Default View Show the results in a datasheet like a table, or a pivot chart or pivot table. Output All Fields This option is usually set to No. If it is changed to Yes, all the fields of all the tables in the query are shown. In general, you should leave this property alone and specify the fields desired in the QBE grid.

Top Values Instead of retrieving all records, you can specify the top n records or n percent, where n is the value specified here. Unique Values By default, this is set to No and all records are retrieved. If you change this to Yes, every record retrieved contains unique values (SQL uses the SELECT DISTINCT command). That is, no retrieved records are identical. For example, you can run a query for the State field of the Patient table. With this set to No, the result is a record for each patient. When set to Yes, only the list of unique states is displayed. When set to Yes, the query is not updateable. Unique Records By default this is set to No and all records are retrieved. For one-table queries, this property is ignored. For multi-table queries, if it is set to Yes, (similar to using a DISTINCTROW in a SQL statement) only unique records in the underlying tables are retrieved. The Unique Records and Unique Values properties are linked and only one can be set to Yes (both can be No). When Unique Records is Yes, Unique Values is automatically set to No. When both properties are set to No, all records are returned. Difference between DISTINCT vs. DISTINCTROW These options sometimes appear to provide the same results, but there are significant differences. DISTINCT checks the results of query and eliminates duplicate rows. These queries (Unique Values = Yes) are not updateable. They are a snapshot of your data and don't reflect subsequent data modifications by users. This is similar to running a Totals Query (for example, using a Group By clause). DISTINCTROW checks all the fields in the table and then eliminates the duplicate rows. The results of a query with DISTINCTROW (Unique Records = Yes) are updateable and reflect changes to retrieved records (but the query does not automatically run again if the data changes to retrieve different rows). So the difference is that DISTINCT only checks the fields in the results, while DISTINCTROW checks all the fields in the underlying tables. If your query joins several tables and only displays records from one, the DISTINCTROW option lets you view and edit the results. For more information, see Distinct versus DistinctRow.

SQL Server Properties There are several properties related to SQL Server tables that are more technical and rarely need to be modified. For more information, refer to the online Help in Microsoft Access. Filter, Order By, Filter On Load, Order By On Load Like a form, you can specify the Filter and Order By settings for a query. However, this is usually part of the query's SQL statement. By using the Filter and Order By properties, you have the extra advantage of specifying the Filter On Load and Order By On Load properties to apply them or not. Subdatasheet Name, Link Fields, and Size If you want to display a subdatasheet to show a one-to-many relationship between the results in this query with data from another table, you can specify them here. There is a significant performance cost for having subdatasheets, so only add them if you really need them. Setting Field Properties In addition to query properties, each field has properties that can be set. Move to a field in the QBE grid and right click. Depending on the field type, different properties are available. The most important properties are for numeric and date fields. You can specify how the fields are formatted when the query is run. Viewing Results and SQL Equivalent Once the query is completed, you can view its results by switching from Design to DataSheet view. You can also view the SQL equivalent. You can even edit the SQL syntax directly and view the results and/or switch to Design view.

Setting Criteria
The bottom section of the QBE grid is several rows for Criteria. These are optional entries to specify which records are retrieved. If you want all the Patients from the state of Virginia, just type VA in the State's criteria. To further narrow the scope, you can type criteria for several fields. Multi-Field Query Criteria Typing criteria on the same row for several fields performs an AND query between the fields. That is, records that match the criteria in field 1 AND the criteria in field 2, and so on are retrieved. If criteria are placed in different rows, an OR query is performed; that is, retrieve all records matching criteria in field 1 OR criteria in field 2, and so on.

Criteria Types The simplest type is the exact match. Just type the value desired in the field's criteria section. Remember that by using the Show option to eliminate the field from the display, you can specify criteria in fields the user never sees. <>, <, >, Between .. And .. You can also retrieve records where a field does not have a particular value by using < > followed by the value that you don't want. Similarly, you can use >, <, >=, or <= for ranges. To select records with values between two values, use the BETWEEN .. AND .. syntax. Nulls To select records with Null values, type Is Null. The opposite is Is Not Null. For text fields, remember that zero length strings ("") are not nulls. OR and IN(.., .., ..) To select records where a field can have one of several values, use the OR command. You can simply say: "MD" or "DC" or "VA". Alternatively, the IN command performs the same function; for example, IN("MD", "DC", "VA"). The second syntax is easier if you have many values. Of course, if you have a very large number of values, it is better to keep those values in a table and link your query to it. That is easier to maintain than OR or IN clauses inside queries. Wildcard Searches Sometimes, you need to search for a particular letter or digit. Combined with the Like command, you can use wildcards to specify such criteria. Microsoft Access uses the following wildcard characters:

? Single character * Any number of characters # Single digit [..] Character list [!..] Not in character list
For example, if you are interested in a text field where the second letter is "a", the criteria would be: Like "?a*". If you were seeking values where the second letter could be an "a" or "e", the criteria would be: Like "?[ae]*". The opposite of this (all values that do not have "a" or "e" as the second letter) is performed by adding an exclamation point (!) as follows:

Like "?[!ae]*". Finally, to select a range of letters (say "a" through "e"), add a dash
between the letters: Like "?[a-e]*".

To search for a wildcard character, enclose the value in brackets. For example, to find values that end in a question mark, use this: Like "*[?]"

Advanced Select Queries


Using Parameters Using Access Functions Using Custom Functions Other Types of Select Queries
(Top Records, Total Queries, Crosstabs, Multi-table Queries, Basing queries on queries)

Percent of Total Frequency Distributions

Using Parameters
Often it is not possible to know in advance the criteria for a query field. In those cases, where the filter values are not known until runtime, a variable (parameter) can be used. When these queries are run, the user is prompted for the value of each parameter. (The parameters can also be assigned programmatically). Using parameters in queries is extremely powerful and converts static "hard-coded" queries to flexible, dynamic ones. The use of parameters can significantly reduce the number of queries you need, makes queries more useful, and simplifies database maintenance. It is easy to add parameters. Instead of typing the value of a criterion, type (between the brackets) the prompt that you want the user to see when the query is run. The value that the user types replaces the parameter in the query. In the following example, a parameter [Enter

State Name:] is the criteria in the [State] field, and [Enter Minimum Age:] is the
parameter in the [Age] field. When this query is run, the user is prompted for the state desired and minimum age, and the records matching that value are retrieved.

Figure 2. Select Query example with two parameters

Parameters work as long as the parameter definition does not conflict with the field name among the query's tables. To better define a parameter, you should specify it in the list of parameters. This is an optional step, but there are good reasons to do so. Right-click the top part of the query and choose Parameters. The following form appears; use the form to list each parameter name and each parameter type.

Figure 3. Query Parameters dialog box

By explicitly defining parameters, users are forced to type values conforming to the type. While it might not matter for text fields, it is useful for numeric and date fields. This minimizes data entry errors that cause a "Can't evaluate expression" error message to appear.

Using Access Functions


One of the most powerful features of Microsoft Access queries is their support for Access functions. This is most useful in Update queries, but can also be used in Select queries. The Advanced: Access Functions query is an example of this feature.

Figure 4. Query using a built-in VBA function

This query selects the Country names in descending order of name length. The second field renames itself to [Length], uses the LEN function to calculate the length of each country name, sorts the length in descending order, and excludes any records with 10 letters or fewer. While this might not seem particularly useful, there are many situations where using Access functions is extremely useful and eliminates the need to program. The string functions in particular (Left$, Right$, Trim$, Mid$, UCase$, LCase$, and so on.) are useful for manipulating portions of strings and changing case.

Using Custom Functions


In addition to using Microsoft Access functions, queries also support user defined functions. Functions defined in VBA modules must return an appropriate value and can be used to manipulate each record. You can reference field values by passing the field name in brackets. Here is an example where a function (StripLead) is used to remove the leading word of a phrase if it starts with "The", "An", or "A". This is useful for sorting phrases such as book titles on "real" words.

Figure 5. Query using a user-defined function

This is the code for the StripLead function. It is passed a string and returns the string without the leading word (if any). VB Copy

Public Function StripLead(pstrPhrase As String) As String ' Comments: Get rid of leading A, An, or The in a phrase. ' Used for card catalog sorting. ' In: pstrPhrase Phrase to examine ' Returns: The input phrase without the "useless" first word. ' Returns the same phrase if the first word isn't an issue Dim strFirstWord As String Dim strReturn As String Dim intPos As Integer strReturn = pstrPhrase intPos = InStr(pstrPhrase, " ") If intPos > 0 Then strFirstWord = Left$(pstrPhrase, intPos - 1) Select Case strFirstWord Case "A", "An", "The" strReturn = Right$(pstrPhrase, Len(pstrPhrase) - intPos) End Select End If StripLead = strReturn End Function

And this is the result. Notice how the sorting of the [Adjusted] field differs from the

[Original] field.

Figure 6. User-defined function results

Other Types of Select Queries


Top Records (number and percent) Total Queries Crosstab Queries Multi-table Queries Basing Queries on Other Queries
Top Records (number and percent) Select queries retrieve all the records that meet your criteria. There are occasions where you only want a subset; the top or bottom number of records. Similarly, you might just want the top or bottom percent of records. Just create a regular Select query that retrieves the records you want. By changing the Top Values query property (right-click the top portion of the query), you can specify the number of records to display. The example below (query: Other: Top 10 Auto Companies) shows only the top 10 records.

Figure 7. Querying the top values

Notice the query is retrieving records in Descending order so the Top Values option retrieves the largest values. It simply runs the query and displays the specified number of records in the query output's order. To display the lowest values, the query should retrieve records in Ascending order. Top Percent of Records Sometimes, you want a percentage of records and not a fixed number. To retrieve the top n% of the query, type a percentage (for example, 10%) instead of a value in the Top Value option. Total Queries Up to now, we have only retrieved records. With lots of data, it is important to calculate summaries for groups of records or totals on the entire table. This is possible by specifying Totals from the Show/Hide ribbon in Access 2007

Figure 8. Specifying Totals from the Ribbon

or by using the View menu in Access 2003 or earlier.

Figure 9. Specifying Totals by using the View menu

This performs calculations across all the records and creates a summary result. For example, you can Sum on a numeric field to determine the total for the entire table. Additionally, you can group on fields to calculate totals for each unique combination of values across the group fields. When Totals is selected, a new Total row appears in the query design. You can specify the type of calculation you want in that section.

Figure 10. Query with totals

For this query, the result shows average Age, Weight and Cholesterol for patients by State and Gender. Crosstab Queries Crosstabs are a powerful analysis tool that lets you quickly see the relationship of data between two fields. The view is a spreadsheet-like display with unique values of one field as rows, unique values of another field as columns, and the summary of another field as the cells in the matrix. For example, with the previous example, a crosstab can clearly show the average Cholesterol between State (rows) and Sex (columns).

Figure 11. Viewing crosstab results

The easiest way to create a crosstab is to use the Crosstab Wizard. When creating a new query, select Query Wizard and then follow the Crosstab Query steps.

Figure 12. New Query Wizard

Crosstab queries can also be manually created by selecting Crosstab from the Query menu and specifying the Row and Column Headings.

Figure 13. Creating a crosstab query manually

Multi-table Queries To this point, all the queries shown were for one table only. Microsoft Access queries allow very sophisticated multi-table queries. Criteria and field selections can be from any of the query's tables. Linking tables on fields is done visually by dragging a line between the fields to link. For our previous example, we might want to show the full name of each state instead of its abbreviation. With a State table that contains the abbreviation and full names, this can be easily performed.

Figure 14. Crosstab of Patients and with State name

Notice the link on the [State] fields and the [Name] field from the States table in the query. To create multi-table queries, the Table row should be displayed. This can be activated from the View | Table Names menu. Even better, the default query options should set Show Table Names to Yes. There are several ways to join tables in a query. The previous example was the most common which is an exact match between fields, sometimes called an inner join. Another join includes retrieving all records from one table regardless of whether there are matches in the second table. This is called a left join. If the logic is reversed (all records from the second table and matching records from the first) it is called a right join. These options can be selected by double-clicking on the linking line and choose among the three options. Left Join Between Tables Here is an example of a query with a left join and the results.

Figure 15. A left join query

Notice how States that do not have patient data are shown with no value in the MaxOfAge and AvgOfCholesterol fields.

Figure 16. Results of a left join query

No Joins Between Tables Queries with multiple tables do not even require a line between the tables. If no lines are specified, a record by record link is assumed. That is every record in the first table is linked to every record in the second table. This is most useful when one of the tables only has one record. Finally, tables can be linked through an expression that establishes a partial match or match based on a range of values. Examples are shown later. Basing Queries on Other Queries So far, the queries presented are only based on tables. However, Microsoft Access lets you also base queries on other queries. This ability to filter and analyze data across several levels is extremely powerful. The queries themselves behave identically whether the data comes from tables or queries. Basing queries on other queries can also simplify maintenance of your database by letting you create standard queries that other queries can use. This can be particularly useful in reports. Of course, you need to be careful modifying the "core" queries. Additionally, when you generate reports in multi-user databases, make sure that you don't use queries when you should use temporary tables that are generated by Make Table and Append

queries. Queries always retrieve the most current data. If you are printing many reports while others are modifying the data, and consistency between reports is important (the numbers need to tie), you must create temporary tables with the data you need prior to printing. You can then base your queries on those "static" tables.

Percent of Total
For a field, calculating the percent of each record to the total for an entire table is useful for determining the relative size of each group. This can be achieved by creating a summary query and using that in another query with the original table. In this example, we use the Fortune100 table containing sales and profits data for 100 large corporations; and two queries (Fortune 100 Totals and Fortune 100 PercentOfTotals). Here is how they work: Step 1: Create a Query calculating the Totals This is a simple query that sums the values in the two fields: Sales and Profits. For clarity, the resulting fields are named TotalSales and TotalProfits.

Figure 17. Totals query with Fortune 100 data

Step 2: Create a Query with the Totals and the Original Table This is a simple select query that retrieves fields from the Fortune100 table and creates new fields for the Percent of Total calculations. Notice the two tables are not linked with lines

between them. They only interact in the Percent of Total calculations where the values in the calculated fields using TotalSales and TotalProfits as divisors.

Figure 18. Fortune 100 percent of Total Sales and Profits

Step 3: Run the Query Running the query provides the desired results.

Figure 19. Results of the query

Notice how the Profit% field shows data nicely formatted (unlike Sales%). The difference is due to formatting settings on the Profit% field. While designing the query, right-click the

Profit% field and notice its format is set to Percent. For the Sales% field, it's a standard
number. This is the reason that the formula for Sales% includes a 100 factor that is not in the

Profit% column.

Frequency Distributions
Frequency distributions reveal the number of records that contain values within numeric ranges. In this example, we want to know how many patients fall into different age categories (under 25, 25 to 40, 40 to 50, 50 to 60, and 60+). A simple two-table query calculates these results even when the size of the numeric ranges are not identical. In this example, we use two tables (Age Groups and Patients), and one query (Frequency: Age Distribution). Just follow these steps:

Step 1: Create a table defining the groups and numeric ranges Create a table defining the groups and numeric ranges. Create a table with four fields: Group ID (counter), Group Name (text), Minimum (number), and Maximum (number). For each record, define the groups and its low and high values.

Figure 20. Define the high and low values for each group in a Group definitions table

Notice how the Maximum value of one record is smaller than the Minimum value of the next record. They cannot be identical or else such values would fall into two groups. In our example, the Age data are integers so using integers in this table is okay. Otherwise, you can use numbers very close to each other (for example, 24.9999999). You can name and specify as many groups as you like. Step 2: Create multi-table Select query Create a Totals Select query with the data table and the Group definition table defined above.

Figure 21. Query to calculate frequency distribution

Notice that the two tables boxes are not linked to each other. The first two fields in the query come from the group table: the Group ID field controlling the sort order, and the Group Name description. The third field is the count of the Patient (data) table's ID field (this field is used because it is not null for every record). The final field defines the link between the two tables. Using the Patient table's Age field, the criterion is Between [Minimum] And [Maximum]. This "bins" the Patient data into the age groups defined by the Group table. Step 3: Run the Query Running the query provides the results

Figure 22. Frequency distribution results

If the Group table's Group ID field is not used in the query, the results would be shown in Ascending order by Group Name (Under 25 would be the last record).

Action Queries
To this point, we have only covered Select queries. These queries take existing data and display it to you either record for record or in a summarized manner. Action queries actually change data. These queries can modify fields, add records to tables, delete records, and even create tables. To specify the query type, select among the options presented under the Query menu while designing a query.

Figure 23. Query Type options on the Ribbon

These queries are similar to creating Select queries. Make Table Queries Make Table Queries are identical to Select queries except that instead of creating a datasheet display of the results, a new table is created containing the results. These are particularly useful for creating temporary tables. For example, if you are generating a series of reports while other people are changing the data, a Make Table query can create a snapshot of your data and allow your reports to work off that table. This lets you create a consistent set of reports. Append Queries Append Queries are also similar to Select queries, but the results are inserted as new records into another table. The field names do not need to match and expressions can also be used. Update Queries Update Queries allow you to modify fields. This is often used to update a field with an expression or data from another table. Delete Queries Delete Queries let you specify the records to be deleted from a table.

Queries in Forms, Reports, and Macros

Queries can be used in forms and reports in a variety of ways. The most common is the Record Source of the form or report. Another useful place is the RowSource of a ComboBox.

Running Queries through Macros


Running a query with a macro is very simple. Just use the OpenQuery command and specify the query name to run. If the query has parameters, the user is prompted for the values. If you are running an Action Query, you can do the same thing; however, Action Queries usually display warning messages prior to changing data. To eliminate such messages, use the SetWarnings command to turn this off and on before and after the query.

Using and Running Queries in VBA Code


There are many ways to run queries through modules. Here are a few examples:

Creating and using a RecordSet based on a saved Select query Assigning parameters in queries Using a SQL string to open a Recordset Running a stored Action query Creating a table with a Make Table Query SQL string
Creating and using a RecordSet based on a saved Select query RecordSets let you programmatically move through a table or query. By assigning a Select query to a RecordSet, you can move through the table. Commands such as MoveNext, MoveFirst, MoveLast, MovePrevious, let you control where you are in the query. By checking the EOF status, you can make sure that you stop at the end of the table. Field values are referenced with a ! and field name (in Access 2.0, you could use "." instead of "!"). VB Copy

Public Sub BrowseQuery_DAO() ' Comments: Browse a query and display its fields in the Immediate ' Window using DAO Const cstrQueryName = "Basics: Top 10 Most Profitable Companies" Dim dbs As DAO.Database Dim rst As DAO.Recordset ' Open pointer to current database Set dbs = CurrentDb ' Open recordset on saved query Set rst = dbs.OpenRecordset(cstrQueryName) ' Display data from one record and move to the next record until

' finished Do While Not rst.EOF Debug.Print "Company: " & rst![Company] & " Sales: " & rst![Sales] & _ " Sales: " & rst![Profits] rst.MoveNext Loop rst.Close dbs.Close End Sub
This example prints the company name and sales in the Immediate Window. Assigning parameters in queries Earlier we showed how to use parameters in queries. If you want to run a query that has parameters from within your code, you must specify the parameters in your code. Otherwise, the user is prompted for the parameter value when the query is executed. To pass a parameter value to a query, you need to create a QueryDef and reference its parameters collection. From there you can specify each of the query's parameters. When you are finished, you can create a recordset from it (if it is a Select query) or execute it if it is an Action query. To learn more about QueryDefs and the parameters collection, refer to the online Help section under QueryDefs. VB Copy

Public Sub RunParameterQuery_DAO(pstrState As String) ' Comments: Runs a query that contains parameters ' Input: pstrState Name of state to select records Const cstrQueryName As String = "Basics: Parameters" Dim dbs As DAO.Database Dim qdf As DAO.QueryDef Dim rst As DAO.Recordset Set dbs = CurrentDb() Set qdf = dbs.QueryDefs(cstrQueryName) qdf.Parameters("State Abbreviation") = pstrState ' Open recordset on the query Set rst = qdf.OpenRecordset() Do While Not rst.EOF Debug.Print ("ID: " & rst![ID] & " State: " & rst![State]) rst.MoveNext Loop rst.Close qdf.Close dbs.Close End Sub

Using a SQL string to open a Recordset Often it is not possible to know a query's specifications in advance. In these situations, the query needs to be programmatically created. This is done be creating a SQL string containing the query to run. The example below shows a simple case, but one can easily create a more complex example where the query string (strSQL) is based on other situations (field values, user selections, and so on.). VB Copy

Public Sub RecordsetFromSQL_DAO() ' Comments: Browse the results of a SQL string and display it in the ' Immediate Window Dim dbs As DAO.Database Dim rst As DAO.Recordset Dim strSQL As String strSQL = "SELECT Left([Company],1) AS Letter, " & _ "Count(Company) AS [Count], " & _ "Avg(Sales) AS AvgOfSales, Avg(Profits) AS AvgOfProfits " & _ "FROM Fortune100 " & _ "GROUP BY Left([Company],1)" ' Open pointer to current database Set dbs = CurrentDb() ' Create recordset based on SQL Set rst = dbs.OpenRecordset(strSQL) Do While Not rst.EOF Debug.Print "Company Letter: " & rst![Letter] & " & _ " Sales: " & rst![AvgOfSales] & " & _ "Profits: " & rst![AvgOfProfits] rst.MoveNext Loop rst.Close dbs.Close End Sub

Running your own query string is identical to the previous examples. Just base a RecordSet on the query string. Running a stored Action query To run a saved Action query, use the query Execute command. The simple procedure below lets you easily run a saved query. Just pass the name of the query and it is performed. VB Copy

Public Sub RunActionQuery_DAO(pstrQueryName As String) ' Comments: Sample code of running a stored (action) query ' Input: pstrQueryName Name of saved query to run DoCmd.SetWarnings False CurrentDb.Execute pstrQueryName DoCmd.SetWarnings True End Sub
This procedure sets up a database variable referencing the current database, and creates a QueryDef based on the query name. The Warning message is temporarily turned off before executing the query and reset afterwards. DoEvents and DBEngine.Idle commands are used to make sure that the Jet Engine has completed its tasks and releases its locks. Creating a table with a Make Table Query SQL string A Make Table query is an Action query and can be run with the Action Query example shown earlier. The only wrinkle here is to make sure that the new table is deleted prior to the Make Table query's execution. Also, the example below shows another way to execute a query without using a QueryDef. VB Copy

Public Sub MakeTableFromSQL_DAO() ' Comments: Sample code running an action query created in a SQL string ' Includes simple error trapping to handle problems creating ' table Const cstrNewTableName As String = "Fortune100 LetterSummary" Dim strSQL As String Dim strError As String ' SQL string to create a new table strSQL = "SELECT Left([Company],1) AS Letter, " & _ "Count(Company) AS [Count], " & _ "Avg(Sales) AS AvgOfSales, Avg(Profits) AS AvgOfProfits " & _ "INTO [" & cstrNewTableName & "] " & _ "FROM Fortune100 " & _ "GROUP BY Left([Company],1)" ' Delete table if it exists On Error Resume Next DoCmd.DeleteObject acTable, cstrNewTableName Err.Clear ' Execute (run) the query CurrentDb.Execute strSQL If Err.Number <> 0 Then strError = Err.Description End If On Error GoTo 0

If strError = "" Then MsgBox "Table: [" & cstrNewTableName & "] created" DoCmd.OpenTable cstrNewTableName Else MsgBox "Error creating table: " & strError End If End Sub
Additional code is provided in the sample database with this article.

Additional Resources from Microsoft


For more information about Access 2007, see the following resources:

Access Developer Portal Access 2007 Resource Center Microsoft Office Developer Center

About the Author


Luke Chung founded FMS in 1986 to provide custom database solutions. He has directed the companys product development and consulting services efforts as the database industry evolved. In addition to being a primary author and designer of many FMS commercial products, Luke has personally provided consulting services to a wide range of clients. A recognized database expert and highly regarded authority in the Microsoft Access developer community, Luke was featured by Microsoft as an Access Hero during the Access 10-year anniversary celebration. Luke is a popular speaker at conferences in the US and Europe, and has published many articles in industry magazines. He is a past president of the Washington, DC chapter of the Entrepreneurs Organization (EO Network), serves on the Fairfax County School Superintendent's Community Advisory Council, and is a graduate of Harvard University with Bachelor and Master Degrees in Engineering and Applied Sciences.

Additional Resources from FMS, Inc.


FMS offers a variety of other resources to help you maximize the value of your Microsoft Access data. Document and Improve Queries with Total Access Analyzer Total Access Analyzer documents your entire database to provide detailed information on each object, where it's used, and recommendations to fix or improve them. Part of the analysis includes Queries. Here are some examples of the results:

Unused Query Detection Afraid to delete queries because you're not sure they're
used? Total Access Analyzer can help with that.

Query Dictionary Report showing detailed information on each query Query Cross-Reference Report showing where each query is used Data Flow Diagram showing how data flows from tables to queries to
queries/forms/reports

Duplicate SQL in Queries and Form/Report record sources and row sources
Advanced Numerical Analysis with Total Access Statistics If you want to extend the power of Access queries with more advanced numerical analysis, learn more about the Total Access Statistics program from FMS. It is the leading Microsoft Access statistical analysis program. It analyzes your Access table, linked table, or query in an MDB, ACCDB or ADP, and puts its results in tables. Generate percentiles, frequency distributions, regressions, correlations, rankings, data normalization, advanced crosstabs, tTests, ANOVA, non-parametrics, probabilities, and so on. Interactive Wizard and VBA programmatic interfaces are included with a runtime distribution library. Adding advanced numerical analysis couldn't be easier! Get more information including a free trial version. Recordset Builder in Total Visual CodeTools If you want to simplify the creation and maintenance of Access/VBA code, learn about the Total Visual CodeTools program from FMS. It helps VB6/VBA developers create new code, clean up existing code, and deliver more robust solutions. Two of its builders related to queries are:

The Recordset Builder lets you point to a database, select a table or query/view, select
all or some of the fields, and automatically generate code to browse, edit, or add records to it. Choose whether you want it to use ADO or DAO, and whether you reference the current database or an external one.

The Long Text/SQL Builder converts SQL from a query into a quoted string that you can
add to your VBA Modules, while handling quotes and smart line continuations so parts like FROM, GROUP BY, WHERE, and so on start new lines. Get more information including a free 30 day trial version. Database Maintenance and Macro Scheduler As you add more data to your database, make sure that you compact it regularly for optimal results and that you make backups. Additionally, check for any tasks that need to run repeatedly, such as a particular set of queries, data downloads, exports, or batch of reports that you must print. You can automate these with a macro or some code. To launch this on a regular schedule, use Total Visual Agent from FMS. Total Visual Agent is a Microsoft Access scheduler to run macros, compact, and other database chores on an hourly, daily, weekly,

monthly, or one time event. Easily manage an unlimited number of databases across your network. Get more information including a free trial version. Other Technical Papers and Tips Here are some other FMS papers related to data that you might find helpful:

Using a Microsoft Access Crosstab Query to Create Monthly Summary Reports without
Code

Microsoft Access and SQL Server Database Normalization Tips The FMS Microsoft Access Help Center
Microsoft Access Consulting Services from FMS FMS also offers custom software development services. If you're in over your head or just don't have time, contact the FMS team. We can help you maintain, enhance, and/or migrate your Microsoft Access applications. Here's more on the FMS Microsoft Access Consulting Services. Community Content Add FAQ Microsoft Access Append versus Make Table Queries We added a new paper to our Microsoft Access Query Help Center that discusses Append (Insert) Queries with a discussion on using it versus Make Table queries Entitled: Microsoft Access Append Query Examples, SQL Syntax, and Errors (Insert Queries) http://www.fmsinc.com/MicrosoftAccess/query/snytax/append-query.html Hope this helps. History

9/16/2011 LukeChung

Microsoft Access Query Help Center We've created a consolidated center with our original papers focused on Microsoft Access Queries. Visit our Microsoft Access Query Help Center, http://www.fmsinc.com/MicrosoftAccess/query/help-center.html, to see the update of this query paper with Microsoft Access 2010 support, and other resources related to:

Designing queries and Data Normalization Tips: http://www.fmsinc.com/tpapers/genaccess/databasenorm.html Using a Microsoft Access Crosstab Query to Create Monthly Summary Reports without Code http://www.fmsinc.com/MicrosoftAccess/query/crosstab-report/index.html Outer join 'not in' queries to find records in one table but not another http://www.fmsinc.com/MicrosoftAccess/query/outer-join/index.html Difference between distinct vs. distinct row syntax http://www.fmsinc.com/MicrosoftAccess/query/distinct_vs_distinctrow/unique_values_re cords.asp Action queries:

o o o o

Update Queries: http://www.fmsinc.com/MicrosoftAccess/query/snytax/update-query.html Delete Queries: http://www.fmsinc.com/MicrosoftAccess/query/snytax/deletequery.html This Recordset is not updateable: Dealing with Non-Updateable Microsoft Access Queries http://www.fmsinc.com/MicrosoftAccess/query/non-updateable/index.html Suppress Warning Messages When Running Microsoft Access Action Queries Programmatically in VBA http://www.fmsinc.com/free/NewTips/Access/RunningActionQueriesProgrammat ically/SuppressWarningMessages.asp Returning the Number of Records or Rows Affected by an Action Query in Microsoft Access with VB6/VBA http://www.fmsinc.com/free/NewTips/Access/RunningActionQueriesProgrammat ically/AffectedRecords/Action_Query.asp

And many other cool tips and techniques for queries Hope this helps. History

6/3/2011 LukeChung

6/3/2011 LukeChung

Update Query SQL Syntax and Dealing with Non-Updateable Queries Here's additional information the UPDATE Query with definitions and examples: http://www.fmsinc.com/MicrosoftAccess/query/snytax/update-query.html A separate paper describing Non-Updateable Queries and using tempoary tables to work around them is available here: http://www.fmsinc.com/MicrosoftAccess/query/non-updateable/index.html History

12/8/2009 LukeChung

Delete Query SQL Syntax and Troubleshooting Here's a supplemental paper describing the DELETE Query in more detail with examples: http://www.fmsinc.com/MicrosoftAccess/query/snytax/delete-query.html There is also a discussion of when the Delete Query fails with this message "Could not delete from the specified tables", what causes it, and workarounds. History

12/8/2009 LukeChung


2012 Microsoft. All rights reserved.

12/8/2009 LukeChung

Terms of Use | Trademarks | Privacy Statement | Feedback Feedback

Das könnte Ihnen auch gefallen