Sunteți pe pagina 1din 155

Crystal Reports XI: Advanced Instructors Edition

ILT Series
COPYRIGHT Axzo Press. All rights reserved. No part of this work may be reproduced, transcribed, or used in any form or by any meansgraphic, electronic, or mechanical, including photocopying, recording, taping, Web distribution, or information storage and retrieval systemswithout the prior written permission of the publisher. For more information, go to www.courseilt.com.

Trademarks
ILT Series is a trademark of Axzo Press. Some of the product names and company names used in this book have been used for identification purposes only and may be trademarks or registered trademarks of their respective manufacturers and sellers.

Disclaimer
We reserve the right to revise this publication and make changes from time to time in its content without notice.

Contents
Introduction
Topic A: Topic B: Topic C: Topic D:

iii

About the manual............................................................................... iv Setting student expectations .............................................................. ix Classroom setup.................................................................................xii Support...............................................................................................xv

Selecting data

1-1

Topic A: Parameter fields ................................................................................ 1-2 Topic B: Defining report elements ................................................................. 1-10 Unit summary: Selecting data ......................................................................... 1-17

Advanced formulas and functions

2-1

Topic A: Running totals................................................................................... 2-2 Topic B: Variables ........................................................................................... 2-7 Topic C: Advanced functions ......................................................................... 2-16 Topic D: Constructs ........................................................................................ 2-22 Unit summary: Advanced formulas and functions.......................................... 2-28

Charts and maps

3-1

Topic A: Working with charts ......................................................................... 3-2 Topic B: Creating maps .................................................................................. 3-13 Unit summary: Charts and maps ..................................................................... 3-20

Formatting complex reports

4-1

Topic A: The Section Expert ........................................................................... 4-2 Topic B: Advanced conditional formatting .................................................... 4-12 Topic C: Objects ............................................................................................. 4-20 Unit summary: Formatting complex reports ................................................... 4-26

Alerts and subreports

5-1

Topic A: Report alerts...................................................................................... 5-2 Topic B: Subreports......................................................................................... 5-7 Unit summary: Alerts and subreports.............................................................. 5-16

Data management features

6-1

Topic A: The Business Objects Enterprise Repository.................................... 6-2 Topic B: The Workbench ................................................................................ 6-7 Unit summary: Data management features ...................................................... 6-9

Advanced data access techniques

7-1

Topic A: ODBC data sources........................................................................... 7-2 Topic B: SQL and the Database Expert.......................................................... 7-10 Unit summary: Advanced data access techniques........................................... 7-20

Course summary

S-1

Topic A: Course summary ............................................................................... S-2 Topic B: Continued learning after class .......................................................... S-4

ii

Crystal Reports XI: Advanced

Quick reference Glossary Index

Q-1 G-1 I-1

xvi

Crystal Reports XI: Advanced

11

Unit 1 Selecting data


Unit time: 95 minutes Complete this unit, and youll know how to:
A Use parameter fields to preview data, based

on specified criteria.
B Select data by using a pick list and a date

range, and create cascading parameters

12

Crystal Reports XI: Advanced

Topic A: Parameter fields


Explanation With Crystal Reports, you can use parameter fields to view only the data you want to see. You can create a parameter field to select a specific value and return only the data in the report that matches that value, or you can specify a range of values. In this way, a report will change depending on which values are selected from the parameter field.

Using parameter fields


A parameter field prompts the user to enter a value and then displays data based on that value. For example, a user may want to display sales data for only those years when product sales were greater than $100,000. You can create a parameter field that prompts the user to specify that or any other amount. When creating a parameter field, you can specify a discrete value or a range of values. If you specify a discrete value, users can enter only a single value in the parameter field. If you use a range, however, users will be prompted to specify lower and upper limits for the parameter field. The report will display the values that fall within the specified range. For example, to display sales between 2003 and 2005, a user can specify these years as the lower and upper limits of a range. You can also use multiple parameter fields. For example, if you want to display data for the sales of a particular product in a particular year, you can create multiple parameter fields to prompt the user for this information. There are several ways to use a parameter field. They include: Placing it in the report Including it in a conditional formatting formula Including it in a record selection formula To create a parameter field: 1 Open a report. 2 In the Field Explorer, select Parameter Fields. 3 Click New, to open the Create Parameter Field dialog box. 4 Enter a name and prompting text for the parameter field, and then specify a value type. The name identifies the parameter field and will appear in the Field Explorer. The prompting text prompts the user to enter a value. The value type specifies the type of data that can be entered in the field, such as string, number, or date time. 5 Click OK.

Selecting data

13

Exhibit 1-1: The Create New Parameter dialog box

14
Do it!

Crystal Reports XI: Advanced

A-1:

Creating a parameter field Heres why


Choose Start, All Programs, Crystal Reports XI.

Heres how
If the registration wizard opens, tell students to click Register Later. Tell students that theyll learn about the Workbench in another unit.

1 Start Crystal Reports XI

Close the Workbench 2 Open Orders Save the report as My Orders

If necessary. From the current unit folder.

Tell students that they can auto-hide the Field Explorer, if they wish.

3 In the Field Explorer, select


Parameter Fields

Click
Tell students that the regional manager wants to run separate reports for each retailer, when needed. Tell students that the data type must match the field.

(The New button is on the toolbar in the Field Explorer.) To open the Create New Parameter dialog box. To specify a name for the parameter field.

4 In the Name box, enter Retailer


Name

In the Type list, verify that String is selected Click OK 5 Open the Select Expert

(As shown in Exhibit 1-1.) This is the parameter fields data type. To close the dialog box and create the new field. (Choose Report, Select Expert, or click the Select Expert button on the Experts toolbar.) To open the Choose Fields dialog box.

In the Report Fields list, select


Retailers.Retailer_Name

Click OK 6 From the list, select is equal to From the second list, select
{?Retailer Name}

The Select Expert dialog box appears. Another list appears. To specify that only those records with the retailer name equal to the parameter value Retailer Name appear when the report is previewed. The question mark (?) before the field name indicates that it is a parameter field. To close the Select Expert.

Click OK

Selecting data 7 Click


Tell students that entries are not case-sensitive.

15

To preview the report. The Enter Values box appears, prompting you to enter a value. The name of the retailer whose records you wish to see. To close the prompt and select the data. Only the records of the specified retailer appear.

8 In the Enter Retailer Name box, type spice world Click OK 9 Observe the report Update the report

16

Crystal Reports XI: Advanced

Wildcards
Explanation Its possible to select records even if youre not sure of the exact value you want to enter at the prompt. You can use wildcards, or a portion of the value name, in a parameter field to return the data youre looking for. For example, you might want to select records based on a name, but you may not be able to remember the exact name you want to select. By using wildcards, you can enter a value and see data that approximately matches that value. A wildcard character is indicated by an asterisk (*). You can use a wildcard character at the beginning or the endor bothof your selection criterion. For example, selecting records based on the value *dill* would return all the product names that include the word "dill," such as "dried dill," "dill weed," and "dill seed." Do it!

A-2:

Using wildcards to select data Heres why


Youll modify the parameter field Retailer Name to select records based on an approximate match to the value entered.

Heres how
Tell students that the regional manager finds it difficult to remember all the retailer names, and wants to type partial names to get the report.

1 Open the Select Expert

2 From the first list, select is like From the second list, select
{?Retailer Name}

Click OK 3 Click Use Saved Data 4 Refresh the report Select Prompt for new
parameter values

To close the Select Expert and apply the change. A dialog box appears. To close the dialog box. Another dialog box appears.

Click OK
Tell students to be sure to type the asterisks.

To open the Enter Values dialog box. To return all records where the retailer name contains the word Spice. To close the prompt and select the new records. The records show only those retailers whose names contain the word Spice. In Select Expert, press Delete, and click OK. To return all the records in the database.

5 Edit the Enter Retailer Name to read *spice* Click OK 6 Observe the report 7 Delete the selection criterion Select Refresh Data Update the report

Selecting data

17

Edit masks
Explanation An edit mask limits the type of data you can enter in a parameter field. For example, you might create a report that prompts the user for an employees Social Security number. Social Security numbers will be displayed in a specific format (###-##-####), where # represents a number when you use an edit mask to ensure that the user enters the number in that format. You can specify an edit mask only for fields using the String data type. There are several characters that you can use to create an edit mask. These are called masking characters. The following table describes some of the masking characters.

Character
A a L C ? & # 9 0 \

Description
The user can enter any alphanumeric character, but the character must be in the parameter value. The user can enter any alphanumeric character but does not need to enter a character in place of the masking character a. The user can enter only letters and must enter a letter in place of the masking character. The user can enter any character or space but does not need to enter a character or space in place of the masking character. The user can enter a letter but does not need to enter a letter in place of the masking character. The user can enter any character or space and must enter a character or space in place of the masking character. The user can enter any digit, space, or plus or minus sign but does not need to enter anything in place of the masking character. The user can enter a number or a space but does not need to enter anything in place of the masking character. The user can enter only numbers and must enter a number in place of the masking character. The character entered after this appears as a literal. For example, if you specify the edit mask 0\L0, then the parameter value will consist of a digit, the letter L, and another digit. This character is useful only when you need to include a reserved masking character as a part of the parameter value. The characters entered after this character are converted to lowercase. The characters entered after this character are converted to uppercase.

< >

18

Crystal Reports XI: Advanced

Character
Password

Description
Here you specify the word Password for an edit mask. When you enter characters for this type of mask, asterisks (*) appear in place of the actual characters. This is useful for creating conditional formulas in which you specify that some fields of the report will appear only when a password is entered. These include periods (.), commas (,), colons (:), semicolons (;), hyphens (-), and slashes (/). Other characters cannot replace these characters, and they form a part of the parameter value. For example, in the case of a Social Security number, the hyphens (-) cannot be replaced by other characters, and they form a part of the parameter value.

Separator characters

To apply an edit mask to a field: 1 Open the Create Parameter Field dialog box. 2 Specify a name, prompting text, and data type for the parameter field. 3 In the Edit mask box, enter the masking characters. 4 Click OK to set the edit mask for the parameter field. 5 Click OK to create the parameter field. When you refresh the data in the parameter field, the Enter Parameter Values dialog box will display the edit mask in the Discrete Value box. Do it!

A-3:

Applying an edit mask to a parameter field Heres why


(In the Field Explorer, click the New button.) To open the Create Parameter Field dialog box. In the Value type list, String should be selected.

Heres how
Tell students that the regional manager wants to view the product sales for a specific retailer code. We will apply an edit mask to a new parameter field because the retailer code is in a specific format.

1 Create a new parameter field In the Name box, enter Retailer


Code

Under Options, in the Prompt text box, type Enter the Retailer
Code for which you want to display order details:

2 Under Options, in the Edit mask box, enter R000

This field can now take only a string that starts with R and is followed by three numbers.

3 Click OK Click OK

To set the edit mask. Retailer Code is added to Parameter Fields in the Field Explorer.

Selecting data 4 Open the Select Expert dialog box Under Report Fields, select
Orders.Retailer_code The Choose Field dialog box appears.

19

Youll apply the Retailer Code parameter to this field. An Orders.Retailer_code tab activated.

Click OK 5 From the list, select is equal to From the second list, select
{?Retailer Code}

To view the records with the Retailer Code equal to the parameter field value. The Enter Values prompt appears.

Click OK 6 In the box, enter T042

Click OK

The entered value is not accepted, because you have not entered all of the required characters. You specified an R in the edit mask, followed by three digits.

7 In the box, enter R042 Click OK Click Refresh Data 8 Delete the selection criterion 9 Refresh and update the report
A message box appears, asking if you want to use saved data or refresh the data. The data for the Retailer Code R042 appears in the report. In Select Expert, press Delete.

110

Crystal Reports XI: Advanced

Topic B: Defining report elements


Explanation You can create parameters that provide users with a list or a range of default values to choose from. This can save time by helping the user to avoid manually typing in a value and possibly making a mistake. If a parameter field has a list of values, you can provide a pick list from which users can choose a particular value. The pick list is also useful in the case when the user is not aware of all the values of the parameter field. You can add values to the list from either an existing text file or a database field. By adding values from a field, you can provide the user with the exact field values. If you use a text file, you can add only those values that are stored in the file, which might differ from the exact values.

Pick lists
To create a pick list from a database field: 1 Create a new parameter field. (You can also modify an existing parameter field.) 2 From the Value Field list, select the field from which you want to create the pick list. 3 From the Description Field list, select a related field, if desired. 4 In the Actions drop-down menu, select Append all database values, to add the values to the pick list. 5 Click OK to close the Create New Parameter dialog box and create the pick list.

Selecting data Do it!

111

B-1:

Using a pick list in a parameter field Heres why

Heres how
1 In the Field Explorer, from the Parameter Fields list, select
Retailer Name

2 Click 3 In the Value Field list, from the Orders table, select
Retailer_code

The Edit button is on the Field Explorer toolbar.

4 In the Description Field list, from the Retailers table, select


Retailer_name

5 Click the Actions drop-down list


Tell students that this action may take a moment or so to complete.

To display a menu. To create a pick list with all the retailer codes and names. To close the Edit Parameter dialog box. To open the Choose Field dialog box.

Choose Append all database


values

Click OK 6 Open the Select Expert In the Report Fields list, from the Retailers table, select
Orders.Retailer_code

Click OK 7 From the list, select is like From the second list, select
{?Retailer Name}

To close the Choose Field dialog box and open the Select Expert.

Click OK 8 Under Enter Retailer Name, click the drop-down arrow Select Outlander Spice
Corner

To close the Select Expert and open the Enter Values prompt. To display the pick list of retailers.

Click OK 9 Update the report

To close the prompt and display the requested records.

112

Crystal Reports XI: Advanced

Selecting multiple values from a pick list


Explanation You can set up a pick list to allow users to select more than one value from it. For example, you may want users to be able to select records containing data for two or more different sales years, or two or more different products. To set up a multiple-value pick list, open the New Parameter or Edit Parameter dialog box, and change the setting for Allow multiple values from False to True. Do it!

B-2:

Modifying a pick list to allow multiple values Heres why


In the Field Explorer.

Heres how
1 Select the Retailer Name parameter field 2 Click 3 Under Options, select Allow
multiple values

To open the Edit Parameter: Retailer Name dialog box.

Click False From the list, select True 4 Click OK 5 From the Available Values list, select R003 Hot Spices Click 6 Select R042 Spice Corner and move it into the Selected Values list Click OK 7 Observe the report Update the report.

To display a list.

To close the dialog box and apply the new setting. The Enter Values prompt appears.

To move the value R003 Hot Spices into the Selected Values list. Select the value from the Available Values list and click the Move button.

To close the dialog box and select the records. It contains records for the two selected retailers.

Selecting data

113

Date ranges
Explanation You can select records based on a range of dates. This is useful when, for example, you want to see data that shows individual department earnings during a particular year, or the product sales for a particular month. To create a parameter field based on a date range: 1 Open the Create New Parameter dialog box (you can also edit an existing parameter). 2 From the Type list, select Date Time. 3 Enter a name and prompting text for the parameter. 4 Create your selection criteria based on a date field. Do it!

B-3:

Using a date range Heres why

Heres how
1 Create a new parameter field named Order Date From the Type list, select Date
Time

2 Under Options, edit the Prompt Text to read Click the


Calendar icon to select order date
Tell students to scroll down the list.

3 In the Options list, change the setting for Allow range values to
True

4 Click OK 5 Open the Select Expert Delete the current selection criterion 6 Create a new selection criterion based on the Orders.Order_Date field, where the operator is equal to the Order Date parameter field. Click OK 7 Observe the screen

To save the settings and close the dialog box.

Press the Delete button.

The Enter Values dialog box appears. The Enter Values dialog box contains two areas for entering selection values.

114

Crystal Reports XI: Advanced 8 In the Start of Range area, click the Calendar icon
To open a calendar.

Tell students to use the arrow icons in the calendar to select the month and year, and to click on the day within the calendar to select the day. If a dialog box appears, tell students to click Refresh Data

Select January 1, 2005 as the Start of Range value Select June 30, 2005 as the End of Range value 9 Click OK 10 Observe the report Update the report

The date appears in the Start of Range box.

Click the Calendar icon in the End of Range area and select the date. To close the Enter Values prompt. Only those records with order dates falling within the specified date range are returned.

Dynamic prompts and cascading parameters


Explanation The prompts you define for a parameter can be either static or dynamic. A static prompt is used when the values associated with it reside in the report itself and do not change. A dynamic prompt can be used when its associated values exist in a data source outside the report, and can change depending on the parameter being prompted for. A dynamic prompt can contain cascading lists of values, meaning that selecting a value from one list filters the values that appear in the following list, and so on. For example, you might want to select records for retailers in a particular city, but you also need to know what state that city is in. You would therefore create the first list based on the state value, and when a state is selected, a list of city values for that state will appear.

Selecting data Do it!

115

B-4:

Creating a cascading parameter Heres why

Heres how
1 Create a new parameter named
Retailer Products

2 In the List of Values options, select Dynamic 3 In the Prompt Group Text box, enter Select a retailer, then
a product

The Static options disappear.

4 Under Choose a Data Source, verify that New is selected Click Insert 5 From the Retailers table, select
Retailer_name To open a list of report fields. This will be the first prompt.

Click as shown

To create the first parameter.

6 Click in the second Value box From the Orders table, select
Product_description

To open the list of report fields. The retailer choice will limit the products that are available to choose when prompted.

In the second Parameters box, click to create the second parameter Click OK 7 Open the Select Expert Delete any current selection criteria 8 Click New Select Retailers.Retailer_name and click OK
Youll create new selection criteria based on the new parameter field. To close the dialog box and create the parameter.

116

Crystal Reports XI: Advanced 9 From the list, select is equal to From the second list, select
{?Retailer Products Retailer_name}

10 Click New From the Fields list, select


Orders. Product_description

To open the Choose Field dialog box.

Click OK 11 From the list, select is equal to From the second list, select
{?Retailer ProductsProduct_description}

To return to the Select Expert.

12 Click OK 13 Preview the report 14 In the first prompt, select All


Times Spices

To close the Select Expert. The Enter Values prompt appears. This retailer has purchased only a limited number of products. To view the list of products that All Times Spices has purchased. To view just the orders for Anise Seeds. To close the prompt and retrieve the records. Only those orders for Anise Seeds are returned.

In the second prompt, click the drop-down arrow 15 Choose Anise Seeds Click OK 16 Update and close the report

Selecting data

117

Unit summary: Selecting data


Topic A Topic B In this topic, you learned about creating new parameter fields. You also learned how to use wildcards in parameters, and to apply edit masks to parameter fields. In this topic, you learned how to create a pick list for a parameter field, and how to select multiple values from pick lists. Next, you learned how to use a date range in a parameter field. Finally, you learned how to create cascading parameters.

Independent practice activity


In this practice activity, youll create a parameter field that will help you select records based on Membership type, and modify the field to allow for various input options. 1 Open Membership List from the current unit folder. 2 Save the report as My membership list. 3 Create a parameter field called Membership Type. Edit the prompt text to read Please Enter the membership type: 4 Create a selection criterion based on the new parameter field. Preview the report, and enter a membership type in the Enter Values box to return records for that membership type. 5 Modify the selection criterion to allow for wildcards. In the Enter Values box, type *b* to return records. 6 Modify the parameter to display a pick list showing all membership types. Refresh the report data and choose Prompt for new parameter values. Choose a membership type from the pick list to return records for that type. 7 Modify the parameter to allow for the selection of multiple values. Test the modification by choosing two values in the Enter Values dialog box. 8 Create a new dynamic parameter named Members. In the Prompt Group Text box, type Choose a membership type, then a member. 9 For the first value, choose strMembershipType. Create an appropriate prompting text. 10 For the second value, choose strLastName Create an appropriate prompting text. 11 Delete all current selection criteria in the Select Expert and create new criteria based on the new parameter fields. 12 Test the selection criteria by entering values in the prompt. 13 Update and close the report.

118

Crystal Reports XI: Advanced

Review questions
1 What is the purpose of a parameter field?
To select a specific value, or a range of values, and return only the data in the report that matches those values.

2 What are some ways you can use a parameter field?

Placing it directly in a report Including it in a conditional formatting formula Including it in a record selection formula
3 When youre not sure of the exact value you want to specify in a parameter prompt, you can: A Enter all the values you can think of in the prompt. B Press the ? key.
C

Use a wildcard (a portion of the value with an *) in the prompt.

D Delete the parameter field so that the prompt doesnt appear. 4 True or false: You can create an edit mask for a parameter field of any data type.
Falseonly the string data type can use an edit mask.

5 A good reason to provide a pick list in a parameter field would be:

To help the user avoid typing in values manually and possibly making a mistake To provide a list of values to the user who may not be aware of all the values available
6 What data type would you choose for a date range parameter field?
Date Time

7 A parameter field that prompts for one value and then supplies a list of related values to choose from is called a: A Static parameter
B

Cascading parameter

C Number parameter D Pick list

21

Unit 2 Advanced formulas and functions


Unit time: 120 minutes Complete this unit, and youll know how to:
A Create, modify, and reset running totals. B Create complex formulas by using

variables, arrays, and ranges.


C Create formulas by using multiple

functions and Evaluation Time functions.


D Specify conditions for repeating sets of

steps in formulas by using For and While loops.

22

Crystal Reports XI: Advanced

Topic A: Running totals


Explanation When creating a report, you might need to calculate an incremental total for a particular field on each record. You perform this function by using running totals. You can identify a running total field by the # sign at the beginning of the running total fields name.

Create a running total


To create a running total field: 1 In the Field Explorer, select Running Total Fields. 2 Click the New button, to open the Create Running Total Field dialog box, as shown in Exhibit 2-1. 3 Complete the dialog box and click OK. The field is then listed in the Field Explorer, under Running Total Fields. 4 Select the field you just created, and drag it onto the report.

Exhibit 2-1: The Create Running Total Field dialog box

Exhibit 2-2: A portion of the report showing a running total

Advanced formulas and functions Do it!

23

A-1:

Creating a running total Heres why


In the current unit folder.

Heres how
1 Open Retailer Order Information Save the report as My retailer
order information

2 In the Field Explorer, select


Running Total Fields

3 Click 4 In the Running Total Name box, type Totals 5 From the Available Tables and Fields list, select Total Amount Click In the Type of summary box, verify that sum is selected Click OK 6 Drag the new Totals field to the Details section of the report, as shown

To open the Create Running Total Field dialog box.

Total Amount is a formula field.

To move the Total Amount field into the Field to summarize box.

To close the dialog box and create the field.

Position it to the right of the Total Amount field.

Drag the Totals field heading to the Group Header #1 section 7 Preview the report Update the report

To align it with the other field headings.

A running total of the product sales is calculated for the Totals field, as shown in Exhibit 2-2.

24

Crystal Reports XI: Advanced

Modify running totals


Explanation You modify a running total field by using the Edit Running Total Field dialog box. You can edit a running total field to make calculations only with specific values or to display information about certain values only. This dialog box appears when you select the running total and click the Edit button in the Field Explorer dialog box. Another method of displaying this dialog box is by rightclicking the running total field and choosing Edit Running Total from the shortcut menu.

Exhibit 2-3: A portion of the report showing the modified Totals field

Advanced formulas and functions Do it!

25

A-2:

Modifying a running total Heres why

Heres how
The regional manager wants to track running totals of products where the Unit Price is greater than $2.00. Tell students that they can also select the field in the Field Explorer and click the Edit button.

1 Switch to Design view

2 In the Details section, right-click the Totals field Choose Edit Running Total 3 Under Evaluate, select Use a
formula

To display a context menu.

To open the Edit Running Total Field dialog box. Youll create a formula to show only those items whose unit price is more that $2.00. To open the Formula Workshop.

Click 4 In the Formula text window, type


{Orders.Unit_price}>2

5 Click Save the formula and close the Formula Workshop 6 Click OK Click Yes 7 Preview the report

To check the formula for errors. On the Formula Workshop toolbar, click Save and close. To close the Edit Running Total field dialog box. A warning message appears. To close the warning message and apply the new formula. The Totals field displays repeating data until a unit price over $2.00 is found, as shown in Exhibit 2-3.

Update the report

26

Crystal Reports XI: Advanced

Resetting running totals


Explanation You may want a running total to reset depending on when a group or a field changes. For example, you might want to reset the running total of a product sale depending on the retailer buying the product. To reset a running total, edit the running total field by selecting an option in the Reset area.

Do it!

A-3:

Resetting a running total based on a group Heres why


The Totals field displays a running total of all sales in all states with unit prices over $2.00. Youll reset the running total to start over with each state, including all unit prices. Right-click the field in the Details section and choose Edit Running Total from the context menu. To include all the unit prices.

Heres how
1 Observe the report

2 For the Totals field, open the Edit Running Total Field dialog box 3 Under Evaluate, select For each
record

4 Under Reset, select On change


of group

To reset the running total when the state group changes. To close the dialog box and apply the new settings. The Totals field now shows a running total of sales for each state. In the Field Explorer.

5 Click OK 6 Preview the report 7 Delete the Totals field Update the report

Advanced formulas and functions

27

Topic B: Variables
Explanation In Crystal Reports, you can perform complex calculations by using formula components such as variables. A variable acts as a placeholder for a specific value. Unlike static values, variables can be assigned different values again and again.

Variables in a formula
All the examples in this unit deal with creating formulas in Crystal syntax. Students can also use Basic syntax to write formulas in Crystal Reports; however, that syntax is not covered in this course.

You might need to create formulas that calculate values based on other calculated values. For example, you have a report that displays production costs and total sales for each year and you want it to display profit as a percentage of production cost. To do so, you first need to calculate the profit by subtracting production cost from total sales. You can then use this value to calculate the profit percentage. To perform this type of calculation, you would store the first calculations result so you could use it in the second calculation. You can do so by using a variable. When a formula comes across a variable, the formula searches for and uses the value attached to that variable. You can store only one value at a time in a variable. Each variable must have a name by which you can identify it. This name cannot be the same as any keyword, function, or operator in Crystal syntax. Variables must also be assigned a data type, such as number, string, or currency. Variable declarations To use a variable in a formula, you must first declare the variable, or specify its data type and name. The syntax for variable declaration is as follows:
<DataType><VariableName>;

The following table describes some of the data types that Crystal Reports uses.

Item
NumberVar CurrencyVar StringVar TimeVar DateVar

Description
Numeric variable Currency variable. (The values that you store in this type of variable are preceded by the currency symbol.) String (text) variable Variable that stores time values in an hours-minutesseconds format, with AM or PM at the end Variable that stores date values in a month-day-year format

For example, heres how you would declare a numeric variable named X:
numberVar X;

To store a value in a variable, you use this syntax:


<VariableName> := <Value>;

For example, this is how you would assign the value 5 to variable X:
X := 5;

28

Crystal Reports XI: Advanced Variable scope Scope defines the degree to which the variable can be used in other formulas. You specify a variables scope when you define the variable. Crystal Reports offers three levels of scope: local, global, and shared. Local variables can be used in only a single formula. To declare a local variable, use the following syntax:
Local numberVar X;

Global variables can be used throughout the main report. The value will be available to all formulas that declare it, but it will not be available within any subreports. To declare a global variable, use the following syntax:
Global numberVar X;

You can also declare a global variable by defaultjust omit the Global keyword. Shared variables are available throughout the main report and all subreports. To declare a shared variable, you precede the declaration with the keyword Shared.

Exhibit 2-4: A portion of the report using the Discounted Price formula

Advanced formulas and functions Do it!

29

B-1:

Declaring and using a variable in a formula Heres why


Youll create a formula that uses variables to determine what month an order was placed, and then applies a discounted rate to that order. In the Field Explorer. To open the Formula Workshop.

Heres how
Outlander Spices discounts some of their overstocked products in certain months. The regional manager wants to run reports that apply the discount for a given month.

1 Switch to Design view

2 Create a new formula field called


Discounted Price

3 In the Operators list, expand


Variable Declarations

4 Double-click NumberVar
x:=y

(NumberVar is the variables data type.) To insert the variable into the formula.

In the Formula text window, after NumberVar, type OrderMonth Position the insertion point after the equal sign 5 In the Functions list, expand
Date and Time Youll add a second value.

Double-click Month(x) 6 In the Report Fields list, doubleclick Orders.Order_Date

To add the function to the formula. The formula will calculate the month in which an order was placed.

7 Position the insertion point after the semi-colon and press e 8 Type the rest of the formula as shown
The code for this formula can be copied from the Discount Price text document in the current unit folder.

To move to the next line of the formula.

If the order date falls in April and June, the discount rate will be 75%. If the order date falls in July and September, the discount rate will be 50%. If the order date is after September, the discount will be 25%.

210

Crystal Reports XI: Advanced 9 Check the formula for errors Save the formula and close the Formula Workshop 10 Place the Discounted Price field in the Details section of the report, as shown

Move the field heading to the Group Header #1 section 11 Format the field heading to match the other headings
Tell students that theyll be adding another field in the next activity.

To align it with the other field headings.

Resize and reposition the field 12 Preview the report

Move it slightly to the left. The discounted price appears, based on the month the order was placed, as shown in Exhibit 2-4.

Update the report

Advanced formulas and functions

211

Arrays
Explanation You may need to use multiple values in a formula. For example, you may have six commission percentages you use based on a salespersons performance. You might also need to change the percentages at some point. Youd have to reflect these changes at all the places where the percentages are used in formulas. This process would be easier if you store the percentages in variables; however, because a variable can store only a single value, youd need to use six variables to store the six percentage values, adding to the formulas complexity. In this type of situation, you can use an array. An array is a kind of variable used to store multiple values of a single data type. To use an array in a formula, you need to declare the array. The syntax is as follows:
<DataType> array <ArrayName> := [Value1,Value2,Value3,....];

For example, heres the syntax for declaring an array named Y that stores four numeric values:
numberVar array Y := [15,20,25,30];

The values that are stored in the arrayin this example, 15, 20, 25, and 30are called the array elements and are referred to by a common name followed by a subscript. A subscript specifies the position of an element in an array. For example, in the array Y, the subscript for element 15 is 1; for element 20, it is 2; and so on. To use the value 15 in the formula, you can refer to it as Y[1]. The subscript of the first value of an array is always 1. The subscript of the last element is called the upper bound of the array. Its the same as the number of elements in an array. To find out the value of the upper bound of an array, you can use a function called UBound. The syntax of the function is:
UBound (<ArrayName>);

This function returns the number of elements in an array as a numeric value, which can be useful when youre using looping constructs.

Exhibit 2-5: The formula edited to use an array variable

212
Do it!

Crystal Reports XI: Advanced

B-2:

Using an array variable in a formula Heres why


Youll modify the current formula to use an array variable to apply the discount.

Heres how
1 Switch to Design view 2 In the Field Explorer, select the Discounted Price field Click 3 Position the insertion point as shown Press e 4 In the Variable Declarations list, double-click NumberVar
array x: = [y, z, ]

To open the Formula Workshop Formula Editor Discounted Price dialog box.

To add a new line for the formula. To add the variable to the formula.

5 Place the insertion point to the left of the colon Type PercentDiscount 6 Enter the remaining values as shown

If necessary.

The code for this formula can be copied from the Array Discount text file in the current unit folder.

7 Edit the remainder of the formula 8 Check the formula for errors Save the formula and close the Formula Workshop

As shown Exhibit 2-5.

Tell students that the discounted prices are the same as in the previous activity, just applied with the array variable.

9 Preview the report Update the report

The discounted price is displayed.

Advanced formulas and functions

213

Range variables
Explanation You use a range in a formula to check whether a value lies between specified limits. For example, in a sales report, you might want to find the names of salespersons whose total sales were between $10,000 and $20,000. A range has two end points: a lower limit and an upper limit. All the values that lie within these limits form part of the range. Heres the syntax for declaring a range variable:
<DataType> range <RangeName> := <LowerLimit> to <UpperLimit>;

For example, to declare a range called sales with a data type of currency, you would use this syntax:
currencyVar range sales := 10000 to 20000;

To check whether a value lies within a range, you can use either the equal sign (=) or the in keyword. For example, the following code will display the text between the quotes if the value of the salesvalue field lies within the sales range:
if Salestable.salesvalue in sales then "The sales value is between 10000 to 20000"

Exhibit 2-6: A formula for displaying text based on range variables

Exhibit 2-7: A portion of the report after the activity

214
Do it!

Crystal Reports XI: Advanced

B-3:

Using a range variable in a formula Heres why


Youll use a range variable to display the total discount. To open the Formula Workshop Formula Text Discount box. To add the range variable to the formula.

Heres how
The regional manager wants to see which discounts are being applied.

1 Switch to Design view 2 Create a new formula field called


Discount

3 In the Variable Declarations list, double-click NumberVar


range x := y to z

4 Place the insertion point to the left of the colon Type Qtr1 Place the insertion point after the equal sign Type 1 to 3

If necessary.

To complete the variable declaration.

5 Add the following variable declarations as shown


Tell students that they can type the declarations directly in the Formula text window.

6 Place the insertion point after the final semi-colon Press e


The code can be inserted from the Range Text text document in the current unit folder.

To begin a new line. As shown in Exhibit 2-6.

7 Type the rest of the formula 8 Check the formula for errors Save the formula and close the Formula Workshop

Advanced formulas and functions 9 Place the Discount field to the right of the Discounted Price field in the report Move the field heading to the Group Header #1 section Format the heading to match the other headings 10 Preview the report Update and close the report
It should look like Exhibit 2-7. To align it with the other headings.

215

216

Crystal Reports XI: Advanced

Topic C: Advanced functions


Explanation To help you create formulas, Crystal Reports provides several types of built-in functions, including String, Summary, Date/Time, and Evaluation Time. You can use these functions by themselves or combine them to form more complex formulas. For example, you can calculate the average sales for the past five years and then round off the values to whole numbers. You can create formulas specific to your needs and speed up creation of reports by combining these functions.

Using multiple functions in a formula


You can create a formula by using multiple functions to calculate a value. You can also combine multiple functions, field values, and text in a formula. Combining functions, field values, and text To combine different types of values in a formula, you use an ampersand (&), which is called the concatenation operator. It combines values from two different types of fields and returns a string type value. You can display this value in the formula field. Consider the following example:
stringVar DisplayValue; DisplayValue := "The sales for the year 2002 are " & Salestable.Sales

This code will combine a string and a sales value, and then store the resulting string in the DisplayValue variable.

Exhibit 2-8: The report showing average profit for 1995 to 2005

Advanced formulas and functions Do it!

217

C-1:

Creating a formula by using multiple functions Heres why


From the current unit folder.

Heres how
Tell students the Vice President of Financial Services wants to view the rounded off average profit for the last eleven years.

1 Open Estimated profit Save the report as My


estimated profit

2 Switch to Design view 3 Create a new formula field named


Average profit

If necessary. The Formula Workshop Formula Editor Average profit window appears.

4 In the Formula text window, type the formula shown:

The formula uses the Average and Round functions to round off the average profit for eleven years. The formula also combines text and calculations by using the concatenation operator (&). (Notice that Crystal syntax will ignore the line breaks in the code.)

5 Check the formula, and click


Save and close

6 Place the new field in the Report Footer section as indicated

Increase the width of the field Format the field with Times New Roman 7 Preview the report Update and close the report

To display all of the text.

It should look like Exhibit 2-8.

218

Crystal Reports XI: Advanced

Evaluation Time functions


Explanation In the process of displaying records, a report goes through three stages: 1 Before the report reads the records from the database 2 While the report reads the records from the database 3 While the report prints the records read from the database Each stage is called a pass. Crystal Reports evaluates the formulas in a report during any one of the passes, depending on the type of formula. Formulas that dont use any database fields are evaluated on the first pass, formulas that use database fields are evaluated during the second pass, and formulas that perform calculations on summary fields, such as subtotals, are evaluated during the third pass. When processing records, Crystal Reports uses Evaluation Time functions internally to decide which formula should be evaluated during which pass. The following table describes the Evaluation Time functions.

Function
BeforeReadingRecords

Description
The formula is executed before the report reads the records from the database. You cannot use any database field in a formula in which you specify this function. The formula is executed for each record as its read from the database. The formula is executed when the report is displaying the records read from the database. This happens after the report has read all the records from the database. This function takes a formula name as an argument. The formula in which you use it will be evaluated after the formula you specify as the EvaluateAfter argument.

WhileReadingRecords WhilePrintingRecords

EvaluateAfter (<FormulaName>)

In some situations, you may need to force a formula to be evaluated during a specific pass. To do this, youll need to include an Evaluation Time function in the formula.

Advanced formulas and functions

219

For example, lets say you have a function that calculates the customer discount and stores it in a variable named DiscountAmount. You also have a function that uses the DiscountAmount variable to calculate the final sales value. In the report, you want to display only the final sales value, but because you wont place the discount formula in the report, its formula wont be evaluated.
To calculate the final sales value, youll need to use the EvaluateAfter function explicitly in the final amount formula by using the customer discount formula as the functions argument. If you do, the customer discount formula will be evaluated first, producing the variable needed to calculate the final sales value.

Exhibit 2-9: The formula for calculating salesperson commission Do it!

C-2:

Using the EvaluateAfter function Heres why


This report already has a formula named Commission that calculates each salespersons commission. Youll create a formula that will calculate total remuneration, which is basic salary ($7000) plus commission.

Heres how
The regional manager wants to track commissions on all sales for the region.

1 Open Commissions

2 Save the report as My


commissions

View the formula for the Commission formula field

(In the Field Explorer, expand Formula Fields, select Commission, and click the Edit button.) The formula, shown in Exhibit 2-9, calculates commissions based on a sliding commission rate.

Close the Formula Workshop window Switch to Design view


(If necessary.) The Commission formula field has not been placed in the report because only the total earnings value needs to be shown. Youll add a formula to calculate the total earnings for each salesperson; this total is the sum of basic salary and commission.

220

Crystal Reports XI: Advanced 3 Create a new formula field named


Total Earnings

Tell students that the formula field will calculate earnings based on the total amounts of the products sold, although the salespeople themselves do not appear in the report.

In the Formula text window, enter the formula shown

This formula stores the salespersons basic salary in a variable named Basic. The formula then declares the variable Commission but doesnt specify a value because the variable should refer to the value of the variable with the same name in the Commission formula. The formula then calculates the sum of the basic salary and the commission.

4 Check the formula, then save it and close the Formula Workshop 5 Place the Total Earnings field in the Details section, as shown Adjust the alignment of the field heading to be consistent with the other headings
Remind students to deselect the field.

If necessary.

6 Preview the report

The Total Earnings field shows all the values as $7000.00, which is the value of each salespersons basic salary. This is because the Commission variable has not been initialized in this formula, nor has the Commission formula been evaluated.

7 In the Field Explorer, select


Total Earnings

(If necessary.) To calculate the correct earnings value, youll use the EvaluateAfter function to force the Commission formula to be evaluated before the Total Earnings formula. To open the Formula Workshop Formula Editor Total Earnings window.

Click

Advanced formulas and functions 8 Place the insertion point in the indicated position

221

Youll enter code above the variable declarations.

Type the following code:


EvaluateAfter ({@Commission}); To evaluate the Commission formula before the Total Earnings formula is evaluated.

Press e 9 Observe the formula

The formula should look like this.

10 Check the formula, save it, and close the Formula Workshop 11 Observe the Total Earnings formula field

The total earnings as a sum of basic salary and commission now appears in the formula. This is because the Commission formula is now forced to execute before the Total Earnings formula.

12 Update and close the report

222

Crystal Reports XI: Advanced

Topic D: Constructs
Explanation You use constructs in a formula to specify which set of steps should be executed and when. Constructs, also called control structures, evaluate a condition to decide whether to execute a set of steps. This process is called looping. The most common constructs are For, While, and If-then-else.

For constructs
You use the For construct when you want to execute a set of steps a certain number of times. Use this construct when you know the exact number of times the steps should execute. The syntax is as follows:
for <VariableName> := <InitialValue> to <FinalValue> step <Value> do ( steps );

A For construct uses a counter variable as a looping counter. The value of this variable at any point in time determines whether the steps inside the parentheses will execute. The construct executes in three steps: 1 It first sets the value of the counter variable to the initial value. This process is called initialization. 2 It then checks whether the value of the counter variable lies between the initial value and the final value, inclusively. This is called a condition test. If the condition evaluates to yes, then the loop condition is true. If the condition evaluates to no, then the loop condition is false. If the condition is true, the construct executes the steps between the parentheses following the do keyword. If not, the loop terminates, and the steps after the construct are executed. 3 It then increases the counter variable by the value specified after the step keyword. This value is called an increment. Steps 2 and 3 are repeated until the condition test becomes false, or when the value of the counter variable exceeds the final value. In the For construct syntax, the initialization, condition test, and increment steps are placed as a single step in the formula. For example:
numberVar i; numberVar j; for i := 1 to 5 step 1 do ( j:= j + 2 );

In this example, the formula begins by declaring variables i and j. The loop initializes the value of i to one (1). The loop will then check whether the value of i lies between 1 and 5. If yes, then it will increment j by two. Then the loop will increment the value of i by one, as specified after the step keyword, and then check the condition again. The steps in this For loop will be executed five times.

Advanced formulas and functions The For construct can terminate in two ways: If the condition in the loop becomes false If an exit for step is specified in the loop

223

Exhibit 2-10: The formula for estimating and displaying profit for the next three years

224
Do it!

Crystal Reports XI: Advanced

D-1:

Using a For construct Heres why


Youll insert a formula in this report to calculate the estimated profit for the next three years based on a profit rise percentage. Youll use the For construct to calculate the estimated profit.

Heres how
1 Open Estimated profit 3 years

2 Save the report as My


estimated profit 3 years

Activate the Design tab 3 Create a new formula named


Estimated profit
The code for this formula can also be inserted from the file Estimated For.txt.

If necessary.

4 In the Formula text window, enter the formula Observe the first two variable declarations Observe the Ctr variable Observe the next two variable declarations

As shown in Exhibit 2-10.

RisePercent and CurrentYrProfit set values for the projected percentage of profit increase and the profits for the current year. This will be the counter in the For construct. The RiseInProfit variable will be used to calculate the projected rise in profit. The FinalString variable will contain the message that the function will ultimately return. The Ctr variable is initialized to 1, the steps are executed, and then Ctr is increased by the step value (1). The construct will execute exactly three times. The steps within the construct calculate each years projected profit, and then combine the FinalString message with some space and the profit value. After the steps execute three times, the FinalString includes all three projected profit values.

5 Observe the For construct

Observe the last step in the formula Check the formula, save it, and then close the Formula Workshop

This line returns the FinalString value.

Advanced formulas and functions 6 Place the Estimated profit field in the Report Footer section, as shown

225

Format the Estimated profit field with Times New Roman Resize the formula field as shown

Remind students to deselect the field. Ask students if they can think of other ways to achieve the same result in a report.

7 Preview the report

To view the estimated profits for all years.

8 Update the report

226

Crystal Reports XI: Advanced

While constructs
Explanation You use a While construct in situations when you dont know the number of times the loop should execute. This construct executes a set of steps repeatedly while a specified condition is true. In the While construct (unlike in a For construct), the steps for initialization, condition test, and increment are placed in separate steps. The syntax is as follows:
while <condition> do ( steps increment step );

Its important to put an increment step within the loop. If you dont, the loop will never end because the value of the counter variable will never change. A While construct can terminate in two ways: If the condition in the construct becomes false If an exit while step is specified in the loop

Exhibit 2-11: The formula using a While construct

Advanced formulas and functions Do it!

227

D-2:

Using a While construct Heres why

Heres how
1 Switch to Design view 2 Create a parameter field named Profit which prompts the user to enter the number of years for which to calculate estimated profit 3 Place the field in the Page Header section of the report 4 Right-click the field and choose
Format Field

The data type for the field should be Number.

To open the Format Editor. Youll suppress the field so that it doesnt appear on the report.

Activate the Common tab Check Suppress Click OK


The code can be inserted from the Estimated While text document in the current unit folder.

To suppress display of the field in the report. To close the Format Editor. As shown in Exhibit 2-11.

5 Edit the formula for the Estimated Profit field 6 Observe the While construct

(In the formula) The While construct determines that the steps will be executed as long as the counter value is less than or equal to the ProfitCount value.

7 Check the formula, save it, and close the Formula Workshop
If a message box appears, tell students to choose Prompt for new parameter values.

8 Preview the report

A prompt appears directing you to enter the number of years for which to calculate estimated profit To calculate estimated profit for the next three years. To close the prompt and retrieve the records. Profits are estimated for three years.

In the prompt, enter 3


If time permits, allow students to enter different values in the prompt.

Click OK 9 Update and close the report

228

Crystal Reports XI: Advanced

Unit summary: Advanced formulas and functions


Topic A In this topic, you learned about running totals. You learned how to create a running total by using the Create Running Total Field dialog box. You also learned how to modify a running total, and how to reset a running total based on a change of group. In this topic, you learned that you can use a variable to store a value. Then, you learned that you can use an array to store multiple values of the same type. You also learned how to use a range variable to test whether a value lies between an upper and a lower limit. In this topic, you learned how to create formulas by using multiple functions. You also learned how to use Evaluation Time functions to specify when a formula should be evaluated. In this topic, you learned how to use looping constructs. You learned that you can use the For construct to execute a set of steps a certain number of times, and you can use the While construct to execute a set of steps while a certain condition is true.

Topic B

Topic C

Topic D

Independent practice activity


In this activity, youll calculate shipping costs by using variables in a formula. Youll also calculate estimated profits for future years, and insert a running total into a report. 1 Open Shipping costs from the current unit folder. 2 Save the report as My shipping costs. 3 Create a new formula called Shipping costs per sale. The formula should calculate total shipping cost for each sale performed. For the formula, declare a number variable named shippingcost. Declare a second number variable named shippingDays that equals the Shipping.Delivery date field minus the Shipping.Shipping date field. The total shipping cost is calculated as the total number of shipping days multiplied by the shipping cost per day. The shipping costs are $50 per day. (The completed code for this formula is in the file Shipping.txt, but first try to build it on your own.) 4 Place the formula after the Delivery date field. Format the field so that its consistent with the other fields in the report. 5 Preview the report and compare it to Exhibit 2-12. 6 Update and close the report. 7 Which Evaluation Time function would you use to perform a formula calculation before the report reads the records to display from the database?
BeforeReadingRecords

8 Which construct would you use to execute a set of steps a known number of times?
The For construct

9 Open Estimated sales from the current unit folder. 10 Save the report as My estimated sales.

Advanced formulas and functions

229

11 Create a new formula called Estimated sales. Calculate the sales for the next five years starting from 2006. Calculate the sales for each year by increasing the previous years sales by 25%. The sales for 2005 should be taken as the current years sales. (The completed code for this is in the file Practice sales.txt, but try building it on your own.) Add the field to the report footer, and then increase the size to show the contents completely. 12 Preview the report and compare it to Exhibit 2-13. 13 For the year field, insert a running total called Year count that displays the year count on each record. (From the Type of summary list, select count.) Place the field in the Details section after Sales, format it to match other fields in the report, and compare it to Exhibit 2-14. 14 Update and close the report.

Exhibit 2-12: The report after step 5 of the Independent Practice Activity

Exhibit 2-13: The report after step 12 of the Independent Practice Activity

230

Crystal Reports XI: Advanced

Exhibit 2-14: The report after step 13 of the Independent Practice Activity

Advanced formulas and functions

231

Review questions
1 What calculation would you insert into a report when you want to show incremental increases in a total?
Running total

2 What is a variable?
An element in a formula that acts as a placeholder for a specific value

3 When you declare a variable in a formula, you ________________.


Specify its data type and name

4 An array variable is a variable that:


A

Stores multiple values of a single data type.

B Allows you to calculate a running total. C Defines a date range. D None of the above. 5 CurrencyVar range sales := 10000 to 50000; is an example of what type of variable?
A range variable

6 What are the stages, or passes, a report goes through in the process of displaying records?

Before reading records from the database While reading records from the database While printing records read from the database
7 What type of function does Crystal Reports use when deciding which formula should be evaluated during which pass?
Evaluation Time function

8 When you know the exact number of times that the steps in a formula should execute, you would use a ______ construct.
For

232

Crystal Reports XI: Advanced

31

Unit 3 Charts and maps


Unit time: 45 minutes Complete this unit, and youll know how to:
A Create and modify charts to provide a

visual representation of data.


B Create and customize maps to represent

data geographically.

32

Crystal Reports XI: Advanced

Topic A: Working with charts


Explanation You add charts to a report to provide a visual representation of data. Charts can help users interpret and analyze data more effectively than simply viewing a set of records.

Creating charts
You can create several types of charts, depending on the type of data you want to display. The following table describes some of the available chart types.

Type
Bar Line

Description
Displays bars of different heights to represent values for sets of data. Use bar charts to display and compare single or multiple sets of data. Plots data as a series of dots joined by a line. This type of chart is useful for analyzing trends. For example, you might use a line chart to view profit trends for the last 10 years. Plots data as color-filled areas on the chart. This type of chart is useful for showing one type of data as a sum of other types. For example, you might want to show the total costs for a year as the sum of production costs and fixed costs. Plots a single set of data, which is represented by divisions of a circle (or slices of a pie). For example, you could use a pie chart to represent four regions sales as percentages of the total sales. Plots only the date values. The data is represented in a horizontal bar chart. For example, you may want to show the schedule of your project. Plots data graphically on a gauge. The data is shown as a set of points and is useful for showing only one group of data.

Area

Pie

Gantt Gauge

The Chart Expert The Chart Expert, as shown in Exhibit 3-1, has several tabs that guide you through the process of creating charts. You use the Chart Expert to specify the type of chart, the data to be plotted, and the chart title, among other things. To create a chart: 1 Choose Insert, Chart to open the Chart Expert. 2 In the Type tab, select the needed chart type. 3 Activate the Data tab, and specify the data to be plotted on the chart. 4 Activate the Text tab, and specify a chart title. 5 Click OK to insert the chart.

Charts and maps

33

Exhibit 3-1: The Chart Expert dialog box

Exhibit 3-2: The Quantity Sold by State bar chart

34
Do it!

Crystal Reports XI: Advanced

A-1:

Creating a chart Heres why


(From the current unit folder.) Youll create a chart showing order data.

Heres how
1 Open Retailer Information 2 Save the report as My retailer
chart

Activate the Design tab 3 Choose Insert, Chart Place the chart in the Report Header section, as shown
An empty square appears in the report.

Click to place the chart. The section enlarges to accommodate the size of the chart.

4 Right-click the chart Choose Chart Expert

To display a context menu. To open the Chart Expert dialog box. The Type tab is active, and gives you several choices for chart type, as shown in Exhibit 3-1. To see thumbnail images of what the types of charts look like. From the chart type list. Youll create a Bar chart. The vertical option will create a chart in upright position. The Horizontal option changes the orientation of the chart by swapping x and y axes. Here, youll specify the field values to be plotted on the chart.

Click on several of the chart types in the list 5 Select Bar Verify that below the list of chart types, the Vertical option is selected. 6 Activate the Data tab Click as shown

To view additional options for creating the chart.

Charts and maps 7 From the Available fields list, select Retailers.State Click, as shown

35

To add the State field to the On change of list. This means that the states will appear on the horizontal or Group axis of the chart. In the drop-down list, the For each record option is used to see values for each record in the report, whereas the For all records option is used to present a summarized value of all records in the report.

8 From the Available fields list, select Orders.Quantity_sold

The chart will show the sums of values from the Quantity_sold field for each year as one series on the chart plotted against the vertical or Data axis.

Click, as shown

To add the Quantity_sold field to the Show value(s) list.

9 Activate the Text tab

On this tab you can specify titles for the entire chart, the axes, and other chart elements. The Auto-Text option tells the Chart Expert to automatically assign titles for the elements.

For the Title box, clear the AutoText check box Edit the text in the Title box to read Quantity Sold by State

Youll replace the auto-text with a custom title.

36

Crystal Reports XI: Advanced 10 Clear the Auto-Text box for the Group title Edit the Group title box to read
States This will be the title for the horizontal axis.

11 Edit the Data title box to read


Quantity sold

Clear the Auto-Text box and enter the new title. This will be the title for the vertical axis. Youll change the font style of the main title.

12 Under Format, verify that Title is selected in the list, and click Font Observe the default font, font style, and size 13 From the Font style list, choose
Bold Italic

The defaults are Arial, Bold, and 13.5.

Click OK Click OK 14 Deselect the chart


Tell students that in Design view, the chart displays only placeholder data. It will look different in Preview.

To close the Font dialog box and apply the new style. To close the Chart Expert and apply the new settings to the chart.

Preview the report

The chart appears as shown in Exhibit 3-2. It displays data for five states, with states plotted on the Group axis, and Quantity sold plotted on the Data axis.

Modifying charts
Explanation After you create a chart, you can modify it by using the Chart Expert, the Chart menu, or both. To modify a chart by using the Chart Expert, select the chart and choose Format, Chart Expert. You can then add data points, set the range and scale of the charts axes, or make any other needed changes. Data points are small labels that show the actual values plotted on the graph. The range sets a minimum and maximum limit for the data to be plotted on a chart. For example, you can set the minimum range to 2000 and the maximum range to 4000 if the data values to be plotted on the chart range from 2000 to 4000. Using a range will accentuate any trends shown in the chart. The minimum range limit is zero by default. The charts scale specifies the division of values on the data axes. The Chart menu Use the Chart menu to format each component of a chart individually. You can also use the Chart menu to modify chart colors and to save the chart as a template. A template stores all the formattingsuch as color, scale, and rangethats applied to the chart. You can use the template to create another chart with the same formatting.

Charts and maps

37

Exhibit 3-3: The Quantity Sold by State chart with data points

Exhibit 3-4: The chart with modified colors and data points

38
Do it!

Crystal Reports XI: Advanced

A-2:

Modifying a chart Heres why


(Youll add data points to your chart to display the actual values represented by the chart.) Youll also change the color of the chart to make it visually more appealing. (If necessary.) Youll use the Chart Expert and Analyzer to modify the chart. (Or right-click the chart and choose Chart Expert from the context menu.) To open the Chart Expert dialog box.

Heres how
1 Activate the Design tab

Select the chart 2 Choose Format,


Chart Expert

3 Activate the Axes tab Under Show gridlines, verify that Major is checked corresponding to the Data axis 4 Under Data values, clear Auto
range (To show the gridlines for the data axis on the chart.) You can select Major or Minor to show the gridlines for the corresponding axes. Youll modify the data range on the Data axis. The Min, Max, and Number format boxes are now available. By raising the minimum of the charts range, you can accentuate the differences between the plotted values.

In the Min box, enter 1

In the Max box, enter 2000 Under Number of divisions, verify that Automatic is selected
To automatically have enough divisions on the chart to represent data meaningfully. You can also select the Manual option and specify the number of divisions.

5 Activate the Options tab Under Data points, check Show


value To display the values of the data plotted in the chart.

Verify that the indicated number format is selected

Verify that Show label is not checked

(To ensure that the chart is not too crowded.) If you select this option, the labels corresponding to the data values also appear alongside the data values, making the chart appear crowded with text.

Charts and maps 6 Under Legend, verify that Show legend is checked and the Placement is selected as Right Click OK 7 Preview the report Observe the Data axis

39

To ensure that the chart's legend appears. You can place the legend to the right, left, or bottom of the chart. To close the Chart Expert dialog box and apply the new settings. All the values now appear as labels by plotted points, as shown in Exhibit 3-3. The scale range now begins at 1, which has the effect of exaggerating the differences between the values in the chart. If necessary.

8 Select the chart Point to a data value, as shown

The value appears in a screen tip.

9 Click the NJ bar of the chart 10 Choose Chart, Format Series


Riser

(The teal or green area.) To select the plotted NJ data. To open the Formatting dialog box. Youll change the color of the selected bar. To open the Color palette.

Under Foreground Color, click the drop-down arrow


Tell students that the colors are identified in screen tips by standard color values. The color they are selecting is 202, 255, 171.

Select the color indicated

Click OK 11 Change the TX bar to a pink color

To close the Format Series Riser dialog box and apply the new color. Select the TX data point and choose Chart, Format Series Riser. Click the Foreground Color arrow and select the color from the palette; then click OK.

310

Crystal Reports XI: Advanced 12 Select the NJ data point label, as shown

13 Right-click the label, and choose


Format Data Label

To open the Format Data Labels dialog box. Youll change the appearance of the labels. To change the font style to bold. To make the data points appear bold. The cost and sale values now appear larger and bold. The chart should look like Exhibit 3-4.

Click
Point out that the formatting is applied to all data labels, not only to the selected label. Remind students to deselect the chart, if necessary.

From the Size list, select 10 Click OK 14 Observe the report 15 Update and close the report

Charts and maps

311

Funnel charts
Explanation Funnel charts are useful for depicting data for various stages of a sales process. The data is represented as a percentage of the total of all stages. The individual stage where a potential problem lies is easily identified so you can also use funnel charts to depict other types of data, such as regional distribution of data. Funnel charts are similar to the stacked bar charts in that they represent the individual share in terms of overall total. The process to create a funnel chart is similar to creating any other chart. To create a funnel chart: 1 Choose Insert, Chart to open the Chart Expert. 2 In the Type tab, select the Funnel chart. 3 Activate the Data tab, and specify the data to be plotted on the chart. 4 Activate the Text tab, and specify a chart title. 5 Click OK to insert the chart. A funnel chart appears, as shown in Exhibit 3-5.

Exhibit 3-5: A funnel chart showing distribution of orders by state

312
Do it!

Crystal Reports XI: Advanced

A-3:

Creating a funnel chart Heres why


Youll make a funnel chart to display the regional distribution of sales.

Heres how
1 Open Retailers 2 Save the report as
My retailer funnel

Activate the Design tab 3 Insert a new chart in the Report Header section 4 Open the Chart Expert From the chart type list, select
Funnel Choose Insert, Chart and place the chart.

Right-click the chart and choose Chart Expert.

5 Activate the Data tab Under Data, verify that Retailers.State is selected In the second list, verify that
Sum of Orders.Quantity_sold

Youll specify the data to be plotted.

is selected 6 Activate the Options tab Under Data points, check


Show Label To display labels for the data points.

7 Activate the Text tab Edit the Title box to read


National Orders Distribution

Youll change the default title of the chart. (Clear the Auto-Text box in order to enter the new title.) You can also give a subtitle and insert a footnote for the funnel chart to make the chart more interactive. To close the Chart Expert and apply the new settings. To view the funnel chart. It appears as shown in Exhibit 3-5.

Click OK
Remind students the chart will look different in Design view.

8 Switch to Preview 9 Update and close the report

Charts and maps

313

Topic B: Creating maps


Explanation You use maps to represent data geographically. For example, you could use a map to show how customers are distributed across a specific city or state. To add a map to a report, use the Map Expert. A map is always linked to a report, because the data represented on the map will change when you change the associated report data.

Creating maps
You can create several types of maps: Ranged map Displays areas in different colors based on the range of values within which the data associated with the areas falls. For example, you could have a ranged map in which regions with more customers will appear in a darker color as compared to regions with fewer customers. Dot Density map Displays dots for each item in a region. In a Dot Density map, a larger number of dots in a specific region represents a higher value. Such maps are useful for population census data. Graduated map Is similar to a Ranged map, except that instead of displaying regions in different colors, a Graduated map displays symbols of different sizes within the regions. The Map Expert The Map Expert has three tabs, as shown in Exhibit 3-6, that guide you through the process of creating a map: 1 Choose Insert, Map to open the Map Expert. The Data tab will be activated. 2 Under Placement, specify whether the map should be placed in the header or the footer. 3 From the Available fields list, specify the fields to be added to the Geographic field box. The geographic field specifies the geographic areas for which the values should appear on the map. For example, this field could contain a list of cities. 4 From the Available fields list, specify the fields to be added to the Map values box. The Map values specify the corresponding values based on which geographic fields will appear on the map. For example, the field to be added to this list could be the number of customers in a city. 5 Activate the Type tab. Here you specify the map type: Ranged, Dot Density, or Graduated. 6 Activate the Text tab. Here you can specify a title and legend for the map. 7 Click OK to add the map to the report.

314

Crystal Reports XI: Advanced

Exhibit 3-6: The Map Expert dialog box

Exhibit 3-7: A map displaying sales by state

Charts and maps Do it!

315

B-1:

Creating a map by using the Map Expert Heres why


Youll add a map to this report to display sales distribution across the United States.

Heres how
1 Open Customer Sales Save the report as
My customer sales

Activate the Design tab 2 Choose Insert, Map

If necessary. (To open the Map Expert, as shown in Exhibit 3-6.) The Data tab is activated by default. Youll place the map in the Report Footer section.

Under Placement, select Footer 3 Under Available Fields, select


Customers.State
Point out that this automatically enters the value into the On change of box.

Click as shown

To add this field to the Geographic field box. This is the field from which geographical regions will be selected for the map.

4 Under Available Fields, select


Customers.Sales

Click, as shown

To add this field to the Map values list. The states will be filled with different colors based on the values in this field.

Observe the Map values list

The colors of the states will be determined by the total sales for each state.

316

Crystal Reports XI: Advanced 5 Activate the Type tab


Ranged is selected by default. This type of map will display the states in different colors based on the range of values in the sales field. The states where total sales are higher will appear in darker colors.

From the Color of highest interval palette, select Maroon, as shown

The states within the highest sales range will be filled with this color.

From the Color of lowest interval palette, select Yellow

The states within the lowest sales range will be filled with this color. States whose sales amount falls between the highest and lowest ranges will appear in shades between the selected Maroon and Yellow colors. The value of Number of intervals specifies the granularity that can be specified to represent data that appear between the highest and lowest ranges. You can specify an integer between 1 and 16 for the Number of intervals. To have an equal number of regions appear in each interval as specified above.

6 Under Options, verify that the number of intervals is 5

Verify that the distribution method is Equal count 7 Activate the Text tab In the Map title box, enter
Customer Sales for Each State

Under Legend, verify that Full legend is selected

To ensure that the full legend appears on the map. You can also opt for a compact legend or no legend at all. In addition, you can specify your own legend title by selecting Specify under Legend title. The Made by map option is selected by default.

Click OK 8 Deselect the map and preview the report

To add the map to the Report Footer section. (Scroll down to view the map.) The map should look like Exhibit 3-7. Notice that Texas, California, and Florida have the most sales. There are some sales in New York and the least amount in Oregon and Louisiana. There are no sales in the other 44 states.

9 Update the report

Charts and maps

317

Customizing maps
Explanation After you create a map, you can modify it by using the Map Expert or the Map menu. You might want to modify a map to change its map type because you feel that another type will better analyze and display the data. The Map menu Here are some ways in which you can modify a map: The Resolve Mismatch option is available only when the map does not recognize some of the values in a geographic field. Use this option to match the map areas with the geographical fields values. To do this, choose Map, Resolve Mismatch to open the Resolve Map Mismatch dialog box, where you can match map keywords with field values. You can use Zoom In or Zoom Out to see larger or smaller views of the map area. You can use the Pan option to move the map with the Panning mouse pointer. This feature is useful when you have a large map and you want to bring a specific area into view.

Exhibit 3-8: The enlarged map with state abbreviations

318
Do it!

Crystal Reports XI: Advanced

B-2:

Customizing a map Heres why


There are only a few states for which the data appears on the map. Youll use the Map menu to customize the map so that only those states appear in the preview. The pointer changes to a magnifier icon.

Heres how
1 Select the map

2 Choose Map, Zoom In Click Texas, as shown

To enlarge the map with Texas at the center.

Deselect the map 3 Observe the report 4 Select the map Click the Zoom In command 5 Click Texas, as shown
Choose Map, Zoom In. An enlarged view of a selected area of the map appears.

To further enlarge the map area.

Charts and maps 6 Right-click the map Observe the commands available in the shortcut menu Choose Layers From the Layers list, select USA Under Properties, check
Automatic Labels

319

To display the shortcut menu. Youll add state name abbreviations to the map. To see the options available for modifying the map. To open the Layer Control dialog box.

Click OK 7 Deselect the map and observe the report 8 Update and close the report

Abbreviations of state names now appear on the map. It should now look like Exhibit 3-8.

320

Crystal Reports XI: Advanced

Unit summary: Charts and maps


Topic A In this topic, you learned how to create charts by using the Chart Expert. You also learned how to modify charts by using the Chart Expert and the Chart menu. Finally, you learned how to create a funnel chart. In this topic, you learned that maps permit you to show data geographically. You learned how to create maps by using the Map Expert, and how to customize them by using the Map menu.

Topic B

Independent practice activity


In this activity, youll create and modify a chart that displays sales data. Youll also create and modify a map that displays a national distribution of profits. 1 Open Quarterly sales report. 2 Save the report as My quarterly sales report. 3 Insert a Bar chart for Quarterly sales in the Report Footer section. Plot the Customers.Quarters field on the Group axis, and the Customers.Sales field on the Data axis. 4 Specify the chart title as Sales, the Group axis title as Quarters - 2005, and the Data axis title as Sales. 5 Display the data points as values on the chart. Format the data points to include dollar signs. 6 Change the size of the data point labels to 11 pt. and make them bold. 7 Preview the report and compare it to Exhibit 3-9. 8 Update and close the report. 9 Open Profit per state and save it as My profit per state. 10 Create a ranged map for statewide distribution of profit. Place it in the report footer and title it Profits for each state. 11 Choose Red from the color of highest interval palette, and Aqua for the color of lowest interval palette. 12 Preview the report. The map should look as shown in Exhibit 3-10. 13 Update and close the report.

Charts and maps

321

Exhibit 3-9: The Quarterly sales report bar chart of sales by quarter

Exhibit 3-10: The map in My profit per state report after completion of step 12

322

Crystal Reports XI: Advanced

Review questions
1 Name four different types of charts used by Crystal Reports.
Bar, Line, Area, Pie, Gantt, Gauge

2 Describe how a bar chart represents data in a report.


It displays bars of different heights to represent values for sets of data.

3 What feature do you use in Crystal Reports to create a chart?


The Chart Expert

4 What is a data point? A A variable in a formula that displays specific data in a chart. B A value in a running total field. C A function that displays a range of values in a chart.
D

A small label that shows actual values plotted on a chart.

5 What type of chart would be useful for displaying distribution of sales data?
Funnel

6 In a ranged map, data is displayed in what manner?


As different-colored areas based on a range of values.

7 What command would you use to enlarge a map area?


Map, Zoom In

41

Unit 4 Formatting complex reports


Unit time: 150 minutes Complete this unit, and youll know how to:
A Arrange field objects by modifying,

adding, merging, and deleting report sections.


B Apply advanced conditional formatting

techniques to a report
C Add hyperlinks and OLE objects.

42

Crystal Reports XI: Advanced

Topic A: The Section Expert


Explanation When you create a report, its objects are arranged in five default sections: Report Header, Page Header, Details, Report Footer, and Page Footer. To improve the reports readability, you can modify, add, delete, or merge the existing sections by using the Section Expert.

Using the Section Expert


Choose Report, Section Expert to open the Section Expert dialog box. The Section Expert dialog box has two panes, as shown in Exhibit 4-1. The left pane contains a list of sections in the report, as well as buttons that permit you to insert, delete, and merge sections. The right pane contains two tabs. The Common tab displays the properties you can apply to the section selected in the left pane. The Color tab permits you to apply a background color to the selected section.

Exhibit 4-1: The Section Expert dialog box

Formatting complex reports

43

Modifying sections
To modify report sections, use the Common tab of the Section Expert dialog box. This tab has several formatting options, as shown in Exhibit 4-1. You can specify a conditional formatting formula by clicking the conditional formula button next to an option. To modify a section, select the section from the Sections list. On the Common tab, check the option you want, and then click OK. The following table describes the options on the Common tab.

Option
Free-form placement Hide (Drill-Down OK) Suppress (No Drill-Down) Print at Bottom of Page New Page Before

What it does
Allows objects to be placed in a free-form environment, rather than at fixed points. Allows the section contents to be available for drill-down, but does not allow them to be printed. Hides a report section so that its not printed or previewed. Forces the section contents to appear at the bottom of the page. Inserts a page break before the section, for every record, the contents of this section will appear on a new page. (This option is available only for the Details, Group Header, and Group Footer sections.) Inserts a page break after the section, for every record, the contents of this section appear at the end of the page, with the next section appearing on a new page. Resets the page number to 1. Keeps all of the sections together. Hides a report section, but only if its blank. Allows a sections contents, such as a logo, to underlay the following sections when printed.

New Page After

Reset page number after Keep together Suppress Blank Section Underlay following sections

44
Do it!

Crystal Reports XI: Advanced

A-1:

Modifying section properties Heres why


In the current unit folder.

Heres how
1 Open Retailer Order Information Save the report as My retailer
order information

Observe the report 2 Choose Report,


Section Expert

A chart is inserted in the Group Header #1 section. To open the Section Expert dialog box. Youll modify the appearance of some of the report sections.

Tell students that they can also right-click the section and choose Section Expert from the context menu.

3 From the Sections list, select


Group Header #1: Retailers.State - A

On the Common tab, check


Hide (Drill-Down OK)

To hide the section. The chart will no longer appear in the report. Notice that some options, such as the option to hide, are not available for this section. Youll change the color of this section.

4 In the Sections list, select


Page Header

Activate the Color tab On the Color tab, check


Background Color

From the Color palette, select


Silver

If necessary.

5 In the Sections list, select


Group Footer #1: Retailers.State - A

Activate the Common tab Check New Page Before 6 Click OK


Tell students to page through the report.

To specify that each group total prints on a new page. To close the Section Expert and apply the new settings. Observe the section changes. The background color for the Page Header section is silver, and the group totals print on the following page.

Preview the report

Update the report

Formatting complex reports

45

Adding sections
Explanation You add new sections by splitting the existing ones. Adding new sections can help you better manage the data on the report. For example, you might want to display the different parts of an address, such as house number, street number, and zip code, in different sections. To add sections: 1 Choose Report, Section Expert to open the Section Expert dialog box. 2 From the Sections list, select a section. 3 Click Insert and the section will split into two new sections with a and b added at the end of the original section name. 4 Click OK to add these sections to the report. You can then arrange the data in these sections. Another way to add new sections is by splitting a section directly in Design view. To do so, place the insertion point at the leftmost boundary of the section. The pointer changes to a Section Splitting pointer, a double-headed arrow with a line through the middle. Click and drag slightly until a horizontal line appears, and release the mouse button where you want the section to be split. Each time you add a new section of the same type, the other sections will be renamed accordingly. For example, in a report that already has sections named Details a and Details b, if you add a section above Details b, the original Details b section will be renamed Details c, and the new section will be named Details b.

Exhibit 4-2: A portion of the report showing the new sections

46
Do it!

Crystal Reports XI: Advanced

A-2:

Adding new sections Heres why

Heres how
1 Switch to Design view 2 Right-click on the Group Header #1: Retailers.State A section Choose Show 3 Open the Section Expert

To display a context menu.

To show the chart in the report. Choose Report, Section Expert, or right-click the Group Header #1 section and choose Section Expert from the menu. If necessary.

In the Sections list, select


Group Header #1: Retailers.State A

4 Click Insert

To add a new Group Header #1 section to the report. Notice that the Group Header #1 section is now split into part a and part b. To close the Section Expert and return to the report. The Group Header #1 section contains two parts. (The Undo button.) To undo the added section. Youll add a section by splitting the Group Header #1 section directly in the layout.

Click OK 5 Observe the report 6 Click

7 In the Group Header #1: Retailers.State A section, position the pointer as shown

(At the 3-inch mark on the ruler.) The pointer becomes a Section Splitting pointer.

Drag down, as shown

A horizontal line appears, showing the upper boundary of the new section.

Release the mouse button

To create the new section.

Formatting complex reports 8 Move the Group #1 Name field to the Group Header #1b section, as shown
Tell students to return to the first page of the report, if necessary.

47

9 Preview the report 10 Switch to Design view Click in the Group Header #1b section Drag to above the Group Header #1a section, as shown, and release the mouse button

The chart displays above the group name. Youll switch the two Group Header #1 sections so that the chart appears after the group name. The pointer changes to a hand.

To move the section. Note that the sections are automatically renamed.

11 Preview the report 12 Add a new Group Footer #1 section to the report Update the report

The chart now appears after the group name, as shown in Exhibit 4-2. Open the Section Expert, select the Group Footer #1 section, click Insert, and click OK.

48

Crystal Reports XI: Advanced

The underlay feature


Explanation Charts can print only in the report header/footer or group header/footer sections of a report. Crystal Reports offers the underlay feature to help you improve your report design and display chart data in a more comprehensible way. By using the underlay feature, you can specify that the section which contains the chart be placed under the section containing the data it represents. By choosing this option, the chart will appear next to the data, rather than above or below it.

Do it!

A-3:

Underlaying a section containing a chart Heres why

Heres how
Tell students that they can also click the Section Expert button on the Experts toolbar.

1 Open the Section Expert 2 From the Sections list, select


Group Header #1b: Retailers.State A Youll redesign the report so that the chart appears next to each states sales data.

3 On the Common tab, check


Underlay Following Sections

To force the section to be placed under the Details section.

Click OK
Tell students to page through the report.

To close the Section Expert. The chart representing data for each state appears next to that states sales figures.

4 Preview the report Update the report

Formatting complex reports

49

Displaying records on separate pages


Explanation When printing a report containing grouped data, you may want to print each group on a separate page. To display one group per page, open the Section Expert, select a section, check New Page After (on the Common tab), and click OK.

Do it!

A-4:

Displaying groups on separate pages Heres why

Heres how
1 Open the Section Expert 2 From the Sections list, select
Group Footer #1: Retailers.State - A

On the Common tab, clear


New Page Before

3 From the Sections list, select


Group Footer #1a: Retailers.State - A

Youll specify that a new page be placed after the group sales totals.

On the Common tab, check


New Page After

To place each group on its own page.

4 Click OK 5 Preview the report Update the report

To close the Section Expert and apply the new settings. Each states sales data appears on its own page.

410

Crystal Reports XI: Advanced

Merging sections
Explanation When you print or preview reports that contain several sections, the fields for a given record may not all appear on the same page. To view these fields, you need to navigate through the report by using the Navigation tool toolbar in the Preview tab. In some cases, you can conserve space in a report by merging some of its sections. When you merge two sections, objects from both sections appear in a single section. To merge sections, open the Section Expert, select a section, and click Merge. You can merge sections only if they are of the same type, such as Details. A section is always merged with the section immediately below it. Do it!

A-5:

Merging report sections Heres why

Heres how
1 In Design view, open the Section Expert 2 From the Sections list, select
Group Footer #1a: Retailers.State A

Youll merge this section with the one below it.

3 Click Merge Click OK Observe the report


Tell students that they will delete the section in the next activity.

To merge the two sections. To close the Section Expert. There is only one Group Footer #1 section. To undo the merge.

4 Click 5 Update the report

Formatting complex reports

411

Deleting sections
Explanation You can delete only those sections you have added; you cannot delete any of the five default sections. When you delete a section, its contents (the field objects) are also deleted from the report. To delete a section, open the Section Expert dialog box, select a section, and click Delete.

Do it!

A-6:

Deleting a section Heres why

Heres how
1 Open the Section Expert 2 From the Sections list, select
Group Footer #1b: Retailers.State - A

3 Click Delete 4 Click OK 5 Observe the report Update and close the report

To delete the section. To close the Section Expert. There is only one Group Footer #1 section.

412

Crystal Reports XI: Advanced

Topic B: Advanced conditional formatting


Explanation Recall that formatting applied to data only under specific conditions is called conditional formatting. The Highlighting Expert can be used for this purpose, but at times, the Highlighting Expert might not contain all the options you need to format fields conditionally. For example, you might want to use styles or font sizes that arent available through the Expert. You might also want to format a field one way if it meets a certain condition, and another way if it meets a different condition. To do this, youll need a more complex formula than you can create with the Highlighting Expert. In such situations, you would use an If-Then-Else formula.

If-Then-Else formulas
In an If-Then-Else formula, you specify a condition to be tested, and then you specify steps to be performed if the condition is true, and, optionally, steps to be performed if the condition is false. For example, you might want to format an employees first name in bold if the employee works in the sales department, and in italics if that employee works in any other department. The If-Then-Else formula for this example would look like the following:
If Employee.Department = "Sales" Then crBold Else crItalic

In this example, crBold and crItalic are the Font-formatting constants for bold and italic, respectively. Two other constants are crRegular, which changes the font style to regular, and crBoldItalic, which changes the font style to bold italic. You can change the color of the font by using Color constants, such as crMaroon, crGreen, and so on. To change the font options conditionally: 1 Select the field and open the Format Editor dialog box. 2 Activate the Font tab, if necessary. 3 Click the formula button next to the font property you want to change conditionally to open the Formula Workshop - Format Formula Editor window. 4 Enter the formula in the Formula text window of the Format Formula Editor window. 5 Save the formula and close the Format Formula Editor window. 6 Click OK to close the Format Editor dialog box and apply the condition.

Formatting complex reports

413

Exhibit 4-3: The Formula Workshop - Format Formula Editor - Font Color window

414
Do it!

Crystal Reports XI: Advanced

B-1:

Using a formula to change a font conditionally Heres why


In the current unit folder.

Heres how
1 Open Orders Save the report as My orders
Tell students that the sales manager wants the codes for those retailers who have ordered more than 140 items to be highlighted in blue and all other codes to be marked in red. Tell students that this is the Conditional formatting button.

2 In the Details section, right-click


Retailer_name

Youll use an If-Then-Else formula to format this field conditionally. (Choose Format Field.) The Paragraph tab is active.

Open the Format Editor dialog box Activate the Font tab 3 Next to the Color box, click Observe the Formula text window 4 Type If Expand Report Fields Double-click
Orders.Quantity_sold

To open the Formula Workshop - Format Formula Editor - Font Color window. It contains comments that direct you to use one of the color codes listed.

If necessary. Orders.Quantity_sold appears in the Formula text section. So far, the formula tests whether the quantity in the Quantity_sold field is greater than 140. This part of the formula formats the text as blue if the condition is true. This part of the formula formats the text as red if the condition is false. The entire formula should look like the one shown in Exhibit 4-3.

In the Formula text section, type


> 140

5 Press q and type


Then crBlue

6 Press q and type


Else crRed

7 Check the formula, save it, and close the Formula Workshop Observe the Format Editor dialog box Click OK 8 Deselect the field and preview the report
The conditional formatting button to the right of Color list appears red, indicating that a condition has been applied. To close the Format Editor dialog box. For items in which the quantity sold is greater than 140, the retailer name appears in blue. For items in which it is equal to or less than 140, the name appears in red.

9 Update and close the report

Formatting complex reports

415

Suppressing report elements conditionally


Explanation You might want to suppress some report elements under certain conditions to improve the reports appearance, or to help the user focus on other aspects of the report. When you suppress a report element, it will not display in Preview, nor will it print. You can suppress report elements based on certain conditions by using a formula.

Do it!

B-2:

Suppressing page numbering on first page only Heres why


In the current unit folder.

Heres how
1 Open Orders by State Save the report as My orders
by state

2 Open the Section Expert 3 In the Sections list, select


Page footer Youll suppress the page number on the first page of the report. To open the Formula Workshop Format Formula Editor Suppress (No Drill-Down) window.

On the Common tab, after the Suppress (No Drill-Down) box, click 4 In the Function tree, expand
Print State

Double-click PageNumber Type =1

To place it in the formula.

If the page number is 1, the page number field will be suppressed in the report.

5 Check the formula, save it, and close the Formula Workshop Click OK
Tell students to scroll down to see the page footer.

To return to the Section Expert.

To close the Section Expert and apply the new formatting. Only Page 1 is suppressed.

6 Preview the report

Update the report

416

Crystal Reports XI: Advanced

Formatting background color conditionally


Explanation You can change the background color of report sections conditionally. For example, you might want to highlight only those sales that are above a certain total. To conditionally format, open the Section Expert, choose the section you wish to format, and create the condition.

Do it!

B-3:

Conditionally formatting a section background color Heres why


Youll format the Details section to display in yellow if certain conditions are met. (From the context menu.)

Heres how
1 Switch to Design view 2 Right-click the Details section and choose Section Expert 3 Activate the Color tab Open the Formula Workshop Format Formula Editor Background Color window 4 Enter the formula shown:

Click the formula button.

Tell students that even though the Order Date field has not been physically placed in the report layout, you can still use it to create formulas.

To change the Details section background color to yellow if the order date is after 1/1/2004 and the quantity sold is greater than or equal to 200. Otherwise, no background color will be displayed.

5 Check the formula, then save it and close the Formula Workshop Click OK 6 Preview the report

To return to the Section Expert.

To close the Section Expert and apply the new condition. The background color is yellow for those retailers whose orders meet the specified conditions.

Update and close the report

Formatting complex reports

417

Using a parameter field in conditional formatting


Explanation You can use parameters as a basis for a conditional format. To do so, simply place your parameter field within the conditional format formula. When you enter a value in the parameter prompt, the condition you specified in the formula is either met, in which case one format will apply, or not met, in which case the format will not apply.

Do it!

B-4:

Using parameters to conditionally format background color Heres why


In the current unit folder.

Heres how
1 Open Target Unit Price Save the report as
My target unit price

2 Create a new number parameter called Target price 3 Open the Format Editor for the Unit_price field Activate the Border tab 4 Open the Formula Workshop Format Formula Editor Background color window 5 Enter the formula shown

Youll create a condition that specifies that items above a certain price appear with a yellow background.

To create a new formula for formatting the background color for the Unit_price field.

To specify that the Unit_price background color will be yellow if it is greater than the Target price parameter.

6 Check the formula, save it, and close the Formula Workshop Click OK 7 Preview the report In the prompt, enter 2 Click OK 8 Observe the report Update and close the report

To return to the Format Editor.

To close the Format Editor. A prompt appears.

To close the prompt. Only those unit prices greater than 2 appear with a yellow background.

418

Crystal Reports XI: Advanced

Conditional formatting for grouped data


Explanation You may have grouped data in your report that takes up more than one page. In this case, its helpful to place text in the report that indicates that the groups data will continue on the next page. To conditionally format a report based on grouped data, create a formula field that specifies that if a groups data continues on a following page, a text string will appear. You can place the formula field in the page header or footer.

Do it!

B-5:

Creating a conditional format for grouped data Heres why


In the current unit folder.

Heres how
1 Open Sales Save the report as My sales 2 Split the Page Header section

To create a Page Header a and a Page Header b section. Youll place new formula fields in the Page Header b section. To open the Formula Workshop Formula Editor GroupContinued window. This formula compares the current state field to the previous state.

3 Create a formula field called


GroupContinued

In the Formula text window, type the formula as shown

4 Check the formula, save it, and close the Formula Workshop 5 Place the GroupContinued field into the Page Header b section, as shown

Suppress the field

Right-click the field and choose Format Field. Activate the Common tab, and check Suppress. To prevent the field from appearing in the report.

6 Create a new formula field named


GroupText

Enter the formula shown

To specify that if the group is continued on the following page, then the specified string will appear on the report.

Formatting complex reports 7 Check the formula, save it, and close the Formula Workshop 8 Place the new field in the Page Header b section of the report
Have students page through the report to see the new text.

419

Next to the GroupContinued field.

9 Preview the report

When the group runs into another page, the specified text displays in the Page Header b section.

10 Update and close the report

420

Crystal Reports XI: Advanced

Topic C: Objects
Explanation In your report, you may want to display data that is saved outside the reports data source. For example, you may have some data in a text file that you want to see when previewing the report, or you may want to add a graphic from another program to the report. To display data from other applications, you can either create a hyperlink that connects to the file, or link, or embed an OLE object.

Hyperlinks
You can create a hyperlink on an object by using the Hyperlink tab of the Format Editor dialog box, as shown in Exhibit 4-4. The Hyperlink type group box contains the options to use six different types of hyperlinks. You can create a hyperlink to refer to a local disk file, a field value, a Web site, or an e-mail address. Under the DHTM Viewer Only area, the Report Part Drilldown option is used to explore in further detail the summary fields and fields in a group header or footer. This option is available only if you are creating a link on an object such as group header or group footer. You can use the Another Report Object option to specify the destination object to which you want to navigate. To create a hyperlink: 1 Select a report object. 2 Choose Format, Hyperlink, to open the Format Editor dialog box. 3 Select the type of hyperlink. 4 In the Hyperlink information box, enter the path of the hyperlinks target. 5 Click OK to create the hyperlink. To access data by using a hyperlink, click the object on which you created the hyperlink.

Formatting complex reports

421

Exhibit 4-4: The Hyperlink tab

422
Do it!

Crystal Reports XI: Advanced

C-1:

Adding a hyperlink Heres why

Heres how
1 Open Profit per state 2 Save the report as
My profit per state

Activate the Design tab 3 Select the indicated text field

(The text field, which is also a report object, is located at the far right of the Page Header section.) On this report object, youll create a hyperlink to the Quarterly sales report target document.
Tell students they can also choose Format, Hyperlink to open the Format Editor dialog box.

Click

(The Insert Hyperlink button is on the Experts toolbar.) The Format Editor dialog box appears, as shown in Exhibit 4-4, with the Hyperlink tab activated. To create a hyperlink to a local file on your computer. The File Name box becomes available. The Open dialog box appears.

Under Hyperlink type, select


A File

Under Hyperlink information, click Browse 4 From the Files of type list, select
All Files

Select Quarterly sales


report

From the current unit folder.

Click Open 5 Click OK 6 Deselect the fields Preview the report

To return to the Format Editor dialog box. The name of the file is inserted in the File Name box. To create the hyperlink.

Formatting complex reports 7 Point as shown

423

Make sure students deselect the field, or they wont be able to view the change in the pointer shape.

The pointer changes to a hand, indicating that the text object is a hyperlink.
Tell students that if a message box appears, click Yes.

Click the hyperlink Close Quarterly Sales

The Quarterly Sales report target document opens.

424

Crystal Reports XI: Advanced

OLE objects
Explanation OLE stands for Object Linking and Embedding, a technology that permits you to add data from one application, called the source, to another application, called the destination. As the name suggests, by using OLE, you can insert linked or embedded objects. When you add a linked OLE object to a report, any changes made to the object in the source application will be reflected in the report. When you add an embedded OLE object to a report, however, any changes made to the object in the source application will not be reflected in the report. You can create a new OLE object or add existing data as an OLE object. When creating a new OLE object, you can only embed it. You cannot link it because there is no source object. When you add an existing object, it can be linked or embedded. To insert an OLE object based on an existing file: 1 Choose Insert, OLE Object to open the Insert Object dialog box. 2 Select Create from File, click Browse, select a file, and click Open. 3 Click OK and the pointer will change to an arrow with a rectangular outline. 4 Click where you want to place the object.

Exhibit 4-5: The Insert Object dialog box Do it!

C-2:

Adding a linked OLE object Heres why

Heres how
1 Activate the Design tab 2 Choose Insert, OLE Object

To open the Insert Object dialog box. Create New is selected by default. The Object Type list appears with the types of objects that you can insert. Youll insert an existing bitmap file as an OLE object. The File box appears in place of the Object Type list. A Browse button also appears.

Select Create from File

Formatting complex reports 3 Click Browse Select approved Click Open


To open the Browse dialog box. In the current unit folder.

425

The full path of the selected file is inserted in the File box. The file type (Bitmap Image) is indicated above the File box. To link the image to the original file. This will ensure that whenever you change the logo file, the changes will automatically be reflected in the report. The dialog box should look like Exhibit 4-5. The pointer takes the shape of an hourglass.

Tell students to observe the changes in contents under Results Group box as they check Link.

4 Check Link

Tell students if they check Display As Icon, an icon representing the image will be inserted in the report instead of the actual image.

Click OK 5 Click the Page Header section, as shown

(Under the Quarterly Reports text object.) To place the image on the report.

6 Deselect all fields, and preview the report


If a program other than Paint is set up as the default editor for bitmaps, then that program will start instead.

The APPROVED stamp image is part of the report.

7 Select the Approved stamp image Double-click the image Close Paint 8 Update the report
The Paint window opens. It displays the bitmap image. You can modify the image here.

Tell students to click Yes if a dialog box appears. Tell students that if they want to delete the linked OLE object from the report, they can right-click the OLE object and from the shortcut menu, choose Delete.

Close the report

426

Crystal Reports XI: Advanced

Unit summary: Formatting complex reports


Topic A In this topic, you learned how to work with sections to organize report objects. You learned that you can use the Section Expert to modify, add, merge, and delete report sections. In this topic, you learned several advanced techniques for conditional formatting. You learned how to use a formula to change a font conditionally, and how to suppress page numbering. In addition, you learned how to conditionally format a section background color, and how to use a parameter to conditionally format background color. Finally, you created a conditional format for grouped data. In this topic, you learned how to create hyperlinks to refer to files in other applications. You also learned how to embed and link OLE objects.

Topic B

Topic C

Independent practice activity


In this activity, youll practice working with sections. Youll also practice applying conditional formats and inserting hyperlinks and OLE objects. 1 Open Market survey (from the current unit folder). 2 Save the report as My market survey. 3 Modify the settings of the Page Header b section so the section does not appear when the report is previewed. 4 Delete the section Page Header c. Preview the report and compare it to Exhibit 4-6. 5 Conditionally format the fonts of the Products Ratings values so that A is displayed in red, and the other values appear in blue. (Hint: In the formula, remember to put A in quotes.) 6 Insert a hyperlink on the text object Click here to view the market survey document for 2005. The hyperlink should point to the text file Market survey for 2005 (in the current unit folder). 7 Using the hyperlink, open the text file Market survey for 2005. 8 Close the text file and update the report. 9 Insert the bitmap image Market research seal as a linked OLE object. Place the OLE object in the Page Header c section to the right of the hyperlinked text object. 10 Deselect the OLE object. 11 Update and close the report.

Formatting complex reports

427

Exhibit 4-6: A portion of My market survey after step 4 of the activity

Exhibit 4-7: The My market survey report after step 11 of the activity

428

Crystal Reports XI: Advanced

Review questions
1 What are the five default sections of a report?
Report Header, Page Header, Details, Page Footer, and Report Footer

2 On the Common tab of the Section Expert, selecting the Suppress (No Drill-Down) option for a particular section will:
Hide a report section so that its not printed or previewed.

3 How can you add a new section to a report?


You can either select a section in the Section Expert and click Insert, or split the section on the Design tab.

4 The underlay feature helps you: A Put a section under a layer that suppresses the data in that section. B Delete sections that are not needed. C Merge two sections and their data into one section.
D

Place a chart so that it appears next to the data it represents in the report, rather than above or below it.

5 True or false: You can delete any section in a report.


False. You can delete only those sections youve added, not any of the five default sections.

6 The following code is an example of what kind of formula?


If Employee.Department = "Human Resources" Then crBold Else crItalic

If-Then-Else

7 How would you use a parameter field to conditionally format an element of your report?
Place the parameter in the conditional format formula.

8 If you want to display data from a file that exists outside your report, you could create a ___________ to that file and place it in the report.
hyperlink

9 What does OLE stand for?


Object Linking and Embedding

10 Whats the difference between a linked OLE object and an embedded OLE object?
When you add a linked OLE object to a report, any changes made to the object in the source application will be reflected in the report. When you add an embedded OLE object to a report, any changes made to the object in the source application will not be reflected in the report.

51

Unit 5 Alerts and subreports


Unit time: 75 minutes Complete this unit, and youll know how to:
A Create, modify, and delete report alerts. B Create and use subreports to display data

from another report, and create captions for on-demand subreports

52

Crystal Reports XI: Advanced

Topic A: Report alerts


Explanation In some cases, you may want to report information only when certain conditions are met. For example, the inventory manager may want to automatically generate an alert when the inventory levels for any product fall below a certain level so that she has enough time to replenish the inventory of that product. By using this feature, you can create report-specific formulas that evaluate conditions you specify and display messages only if those conditions are true.

Creating report alerts


You create report alerts by using the Create Alerts dialog box, as shown in Exhibit 5-1. Choose Reports, Create Alerts and then click New. In this dialog box, you specify a name for the alert, the condition that will trigger it, and the message it will display. You use the Create Alerts dialog box to create new alerts or modify existing ones.

Exhibit 5-1: The Create Alerts dialog box When you preview a report with an alert, if the alert condition is met, the Report Alerts dialog box appears, as shown in Exhibit 5-2.

Exhibit 5-2: The Report Alerts dialog box To view the records that generated the alert, you need to click View Records in the Report Alerts dialog box.

Alerts and subreports

53

Exhibit 5-3: The records of sales meeting the alert condition Do it!

A-1:

Creating a report alert Heres why


In the current unit folder.

Heres how
Tell students the sales manager wants to create a report of items that are not selling well. He wants to list all the products that have sales of less than $5000.

1 Open Product sales 2 Save the report as


My product sales

3 Choose Report, Alerts,


Create or Modify Alerts

To open the Create Alerts dialog box.

Click New

To open the Create Alert dialog box.

4 In the Name box, type


Sales below $5000

This will be the name of the alert.

In the Message box, enter Sales


of one or more products have fallen below $5000

To specify the default message that will appear whenever the alert is triggered.

5 Click Condition

To open the Formula Workshop - Alert Condition Formula Editor window, where youll enter an alert condition formula. This formula will test for sales values that are less than 5000.

In the Formula text window, enter the formula shown:

6 Check the formula, save it, and close the Formula Workshop

54

Crystal Reports XI: Advanced 7 Click OK Click Close 8 Preview the report
(In the Create Alert dialog box.) The Create Alerts dialog box should look like Exhibit 5-1. To close the Create Alerts dialog box. The Report Alerts dialog box, as shown in Exhibit 5-2, appears. This dialog box lists the name and message of the alert that was triggered on processing the report. To view the records of items that satisfy the condition specified in the alert. A new tab, Sales below $5000, is added next to the Preview tab. Notice that the sales value field in all the listed records is less than $5000, as shown in Exhibit 5-3.

9 Click View Records

10 Update the report

Modifying report alerts


Explanation To modify a report alert, select the alert you want to edit in the Create Alerts dialog box and click Edit. In the Edit Alert dialog box, you can change the name, message, or condition for the alert.

Exhibit 5-4: The report for the products whose total sales are less than $4000

Alerts and subreports Do it!

55

A-2:

Modifying a report alert Heres why


(To modify the alert.) You cannot modify the alert while the Sales below $5000 tab is active. (Choose Report, Alerts, Create or Modify Alerts.) The Report Alerts box appears, warning you that you cannot perform this command and keep the Alerting tabs and that if you continue, the Alerting tabs will be closed. (To close the alert box and open the Create Alerts dialog box.) Youll modify the report alert. To open the Edit Alert dialog box.

Heres how
Tell students that the sales manager now wants to have only those products listed whose sales are less than $4000.

1 Activate the Design tab 2 Open the Create Alerts dialog box

Click OK

3 Click Edit 4 Change the name of the alert to Sales below $4000 and change the message to reflect the new condition 5 Click Condition Edit the formula to reflect the new condition Check the formula, save it, and close the window 6 Click OK Click Close 7 Preview the report Refresh the report Click OK View the selected records

To open the Formula Workshop - Alert Condition Formula Editor dialog box.

(In the Edit Alert dialog box.) To accept the modifications. To close the Create Alerts dialog box.

The refresh data message appears. To close the message box and display the Report Alerts dialog box. (Click View Records.) The record for Carob Powder with product id P005 has been removed from the list because its sales value is $4000, as shown in Exhibit 5-4.

8 Activate the Design tab Update the report

56

Crystal Reports XI: Advanced

Deleting report alerts


Explanation You can delete any or all the report alerts in a report. To delete an alert, open the Create Alerts dialog box, select the alert you want to delete, and click Delete.

Do it!

A-3:

Deleting a report alert Heres why


A message box appears. To close the Alerting tabs. Youll delete this alert.

Heres how
1 Open the Create Alerts dialog box Click OK 2 Verify that the Sales below $4000 alert is selected Click Delete Click Close 3 Preview the report 4 Choose Report, Alerts,
Triggered Alerts
Tell students that if they now refresh the report, the Report Alert dialog box will not appear.

To open the Report Alerts dialog box. Notice that the box is empty.

Click Close 5 Update and close the report

Alerts and subreports

57

Topic B: Subreports
Explanation When creating a report, you may want to display related data from another report. For example, in an inventory stock report, you may need to add information about suppliers. To do this, you can create a subreport. A subreport is contained within the primary or container report and cannot be previewed separately. There are two types of subreports: unlinked and linked. You can use an existing report as a subreport, or you can create a new one. When you insert a subreport, a new tab with the subreport name is added to the report window, in addition to the Design and Preview tabs. When you want to add multiple subreports to a container report and you dont need to preview all of them simultaneously, you can add them as on-demand subreports. An ondemand subreport appears as a hyperlink in the container. You can view the full subreport by clicking the hyperlink.

Unlinked subreports
An unlinked subreport is an independent report. Its data is not linked or coordinated with data in the container report, nor is any attempt made to match its records to those in the container report. A container report may have an unlinked subreport which contains some data related to the data in the container report. For example, a container report for the sales year of 2006 may contain a subreport for the year 2005, and the user can immediately view the sales data for both years from within the same report. To insert an unlinked subreport into a container report: 1 Open the report in which you want to insert the subreport. 2 Choose Insert, Subreport to open the Insert Subreport dialog box, as shown in Exhibit 5-5. 3 You can create a new subreport or insert an existing report: To insert an existing report, select Choose a report and specify the report file name. To create a new subreport, select Create a subreport with the Report Wizard, specify a report name, and follow the prompts to complete the procedure. 4 Click OK to create the subreport. The pointer will change to an arrow with a rectangular outline. 5 In the primary report, click the location where you want to place the subreport.

58

Crystal Reports XI: Advanced

Exhibit 5-5: The Insert Subreport dialog box

Exhibit 5-6: A portion of My retailer order information with the subreport included

Alerts and subreports Do it!

59

B-1:

Creating an unlinked subreport Heres why


In the current unit folder.

Heres how
1 Open Retailer Order Information Save the report as My retailer
order information

2 Choose Insert, Subreport Select Choose an existing


report

To open the Insert Subreport dialog box. The Subreport tab is active.

Click Browse 3 Select the Profit per state report Click Open Click OK 4 Place the subreport in the Report Footer section, as shown Resize the subreport, as show

The Open dialog box appears. This will be the subreport. To select the subreport and return to the Insert Subreport dialog box. To close the Insert Subreport dialog box.

So that its approximately 2.5 inches wide.

5 Preview the report Update the report

The subreport appears on the last page of the report, as shown in Exhibit 5-6.

510

Crystal Reports XI: Advanced

Linked subreports
Explanation You may want to create a subreport in which the data changes based on what the user previews in the container report. For example, you may create a report that prompts the user for a year and displays that years total cost, profit, and sales data. You can then add a subreport that displays the sales for each product for that year. Data in a linked subreport is coordinated with data in the primary report, and the records displayed in the subreport match those displayed in the main report. The two reports are linked on a common field. To insert a linked subreport: 1 Open a report. 2 Open the Insert Subreport dialog box. 3 Create a new subreport or insert an existing report. 4 Activate the Link tab. 5 Specify the field you want to use to link the container and the subreport, and then click OK. The pointer changes to an arrow with a rectangular outline. 6 Click anywhere in the report to place the subreport.

Exhibit 5-7: The Link tab of the Insert Subreport dialog box

Alerts and subreports

511

Exhibit 5-8: The report with a linked subreport

512
Do it!

Crystal Reports XI: Advanced

B-2:

Creating a linked subreport Heres why


Youll create a subreport linked to a particular field. (Right-click the Details section and choose Insert Section Below.) This is where youll place the new subreport.

Heres how
1 Switch to Design view 2 Insert a new Details section

3 Choose Insert, Subreport Select Choose an existing report Browse to and open
Retailer List In the current unit folder.

4 Activate the Link tab In the Available Fields list, in the Retailers table, select
Retailer_code

Youll select the field in the container report to link to the subreport.

Click Click OK 5 Place the subreport in the Details b section Resize the subreport
Tell students that the preview might take a moment to display as the report adds new pages.

To create the link. The screen should look like Exhibit 5-7. To close the dialog box. Under the Retailer Name field.

Make it approximately three inches wide. The subreport links to the Retailer_code field and displays the retailer name and address for each order, as shown in Exhibit 5-8.

6 Preview the report

Alerts and subreports

513

On-demand subreports
Explanation When you want to add multiple subreports to a container report and you dont need to preview all of them simultaneously, you can add them as on-demand subreports. An ondemand subreport appears as a hyperlink in the container. You can view the full subreport by clicking the hyperlink. To make the subreport appear as a hyperlink in the primary report, check On-demand subreport in the Insert Subreport dialog box.

Do it!

B-3:

Creating an on-demand subreport Heres why


Youll modify the last inserted subreport so that it is an on-demand subreport In the Details b section. To open a context menu. To open the Format Editor dialog box.

Heres how
1 Switch to Design view 2 Right-click the Retailer List subreport 3 Choose Format Subreport Activate the Subreport tab 4 Under Subreport options, check
On-demand Subreport

To convert Retailer List to an on-demand subreport. To close the Format Editor and apply the new setting. Instead of the retailer address data itself, the name of the subreport, Retailer List, appears in the details section.

Click OK 5 Deselect the subreport and preview the report Position the mouse pointer as shown

The pointer changes to a hand, showing that the subreport is now on-demand, similar to a hyperlink.

6 Click the mouse Update the report

Address information for Marys Market appears in a new Preview tab.

514

Crystal Reports XI: Advanced

Creating captions for on-demand subreports


Explanation By default, an on-demand subreport will appear with the title of the actual subreport, such as Accounts.rpt or Customer List.rpt. You can create a caption, either for the placeholder frame or the preview tab text, that is more descriptive of the subreports content by using a formula. To do so: 1 In Design view, select the subreport and choose Format, Subreport to open the Format Editor. 2 Activate the Subreport tab. 3 Depending on whether you want to caption the on-demand subreport or the preview tab, click the appropriate formula button to open the Formula Workshop. 4 Enter the formula, check for errors, save, and close the Formula Workshop.

Exhibit 5-9: The on-demand subreport with a caption

Alerts and subreports Do it!

515

B-4:

Creating a caption for an on-demand subreport Heres why


Youll add a caption to the placeholder frame for the on-demand subreport. The Retailer List.rpt. To open the Format Editor dialog box.

Heres how
1 Switch to Design view 2 Select the on-demand subreport
Tell students that they can also right-click the subreport and choose Format, Subreport from the context menu.

Choose Format, Subreport 3 Activate the Subreport tab Next to On-demand Subreport Caption, click 4 In the Formula text window, enter the formula shown

To open the Formula Workshop Format Formula Editor On-demand Subreport Caption. To display a text string that specifies the retailers by name.

5 Check the formula for errors Save the formula and close the Formula Workshop Click OK
Tell students to enlarge the subreport frame, if they wish.

To close the Format Editor. The new caption replaces the subreports title, as shown in Exhibit 5-9.

6 Deselect the subreport and preview the report Update and close the report

516

Crystal Reports XI: Advanced

Unit summary: Alerts and subreports


Topic A Topic B In this topic, you learned how to create, modify, and delete report alerts. You learned that report alerts can display messages when certain conditions are met. In this topic, you learned how to create subreports. You also learned that the data in an unlinked subreport is not coordinated with that of its container report, whereas the data in a linked subreport changes based on what the user previews in the container report. Finally, you learned how to create an on-demand subreport, and to create a caption for the on-demand subreport.

Independent practice activity


In this activity, youll practice creating, modifying, and deleting a report alert. Youll also practice working with subreports. 1 Open Retail Orders in the current unit folder. 2 Save the report as My retail orders. 3 Create an alert that is triggered by total state sales below $1500. Name the alert State sales below $1500 and specify the message as Retail sales in some states have fallen below $1500. (Hint: For the condition, use the summary field Group #1: Retailers.State A: Sum of @Total sale.) 4 Refresh the report data and choose View Records when the alert is triggered. Compare your report to Exhibit 5-10. 5 Modify the report alert so that it is triggered when state retail sales fall below $1000. Refresh the report data with the new alert and view the records. 6 Delete the report alert. 7 Create an unlinked subreport by using Product Sales in the current unit folder. Place the subreport in the Report Footer section of My retail orders. 8 Modify the unlinked subreport so that it is an on-demand subreport. 9 Preview the report. The last page of the report should look like Exhibit 5-11. 10 Create a linked subreport using RetailerSubreport in the current unit folder, linking to the Retailer_name field. Place the subreport in a new Details section of My retail orders. 11 Convert the subreport to an on-demand subreport, and create a caption for it that reads: Address information for [Retailer name]. 12 Preview the report. It should look like Exhibit 5-12. 13 Update and close the report.

Alerts and subreports

517

Exhibit 5-10: A portion of the report after step 4 of the Independent Practice Activity

Exhibit 5-11: The report showing the unlinked, on-demand subreport

Exhibit 5-12: A portion of the report after step 11 of the activity

518

Crystal Reports XI: Advanced

Review questions
1 A report alert is triggered when:
A

A condition you specify for the alert is true.

B The report is opened. C A record is deleted from the report. D The data is refreshed. 2 The command to create a report alert is: A Insert, Report Alert
B

Report, Alerts, Create or Modify Alerts

C Database, Database Expert, Create or Modify Alerts D Report, Alerts, Triggered Alerts. 3 What are the two types of subreports?
Unlinked and linked

4 What is the difference between the two types of subreports?


An unlinked subreport is an independent report whose data is not linked or coordinated with data in the container report. A linked subreport is linked to the primary report on a common field, and the records displayed in the subreport match those displayed in the main report.

5 An on-demand subreport:
A

Appears as a hyperlink in the container report.

B Displays its data in the footer section of the container report C Cannot appear more than once in the container report. D Appears by default as On-demand subreport in the container report.

61

Unit 6 Data management features


Unit time: 45 minutes Complete this unit, and youll know how to:
A Use the Repository Explorer to insert

report items from a central location


B Use the Workbench feature to manage

report projects.

62

Crystal Reports XI: Advanced

Topic A: The Business Objects Enterprise Repository


Explanation The Business Objects Enterprise Repository is a database for storing text and graphic objects, as well as custom functions, commands, bitmaps, and Business Views. These stored items can then be added to any report without requiring you to recreate the objects from report to report. When you make a change to an item in the repository, Crystal Reports updates all the reports that contain that item. A central location for report objects makes data management easier and helps to increase your productivity.

Add items to the repository


Items in a report can be added to the repository by using the Add Item dialog box. To open this dialog box, you right-click an item and choose Add to Repository. Next, provide the necessary details, such as name, author, and description to identify the item. Finally, identify where in the repository the object will be stored and click OK.

Exhibit 6-1: The Add Item dialog box

Data management features Do it!

63

A-1:

Adding an item Heres why


From the current unit folder. (Located at the bottom of the page.) It contains a text object stating that the report data is confidential. Youll add this text object to the repository.

Heres how
1 Open Repository report In the report, observe the Page Footer section

2 Save the report as


My repository report

3 Choose View,
Repository Explorer

To open Repository Explorer.

Click Logon

On the Repository Explorer toolbar. To open the Log On to Business Objects Enterprise dialog box. If necessary. Youll log on with this account. No password is necessary. To log on. (On the Repository Explorer toolbar.) Youll create a new folder and name it.

In the User name box, enter


Administrator

Click OK 4 Select the folder


Repository Items

and click Edit the new folder name to read


Text objects

5 Activate the Design tab 6 In the Page Footer section, rightclick Confidential From the context menu, choose
Add to Repository

If necessary. (A context menu appears.) Youll add this text object to the repository. To display the Add Item dialog box.

7 In the Name box, enter


Confidential

To provide a name to the text object that will be shown when it is added to the repository.

Edit the Author box to read


Outlander Spices

In the Description box, enter This


is a confidential report.

The Add Item dialog box should look similar to the one shown in Exhibit 6-1.

64

Crystal Reports XI: Advanced 8 Under Location, expand the toplevel object Select Text Objects Click OK
(If necessary.) To display the folders in the repository, such as Dynamic Cascading Prompts and Text Objects. To add the Confidential text object under Text Objects. To close the Add Item dialog box and add the text object to the repository.

Tell students that the toplevel objects on their screens might look different than those in the screen shots.

Tell students that their screens may look different than what is pictured here.

9 In the Repository Explorer, expand Text Objects

The Confidential text object is added under Text Objects in the repository.

Use repository items in reports


Explanation You can add objects in the repository to a report by dragging them from the repository to the appropriate section of the report.

Do it!

A-2:

Using a repository item in a report Heres why


To view the images added in the repository.

Heres how
1 In Repository Explorer, expand
Images

2 Drag Outlander Logo to the Report Header section of the report, as shown

3 Preview the report

The logo is added to the Report Header section.

4 Update the report

Data management features

65

Modify items in the repository


Explanation After an object has been stored in the repository and then added to various reports, it is possible to modify that object and have each instance of it updated. To modify a repository item, you must first disconnect it from the repository. The object is updated when the report is opened. To modify an item in the repository: 1 In the report, right-click the object you want to modify. 2 Choose Disconnect from Repository in the context menu. 3 Edit the report object. 4 Drag the edited object back to the original object in the Repository Explorer and choose Update in the message box. Do it!

A-3:

Modifying an item Heres why

Heres how
1 Activate the Design tab 2 In the Page Footer section, rightclick Confidential Choose Disconnect from
Repository

To display a context menu. Youll modify the text in the text object. You have to disconnect the object from the repository to modify it. To place the text object in edit mode. The object now has a marquee around it and a flashing insertion point inside it.

3 In the Page Footer section, double-click Confidential Edit the text object to read
Confidential Report

4 Deselect all fields 5 Drag Confidential Report from the Page Footer section and drop it on Confidential in Repository Explorer Click Update Click OK 6 Delete the text object from the Page Footer section 7 Drag a copy of Confidential from the repository to the Page Footer section 8 Update the report
The Add or update object? dialog box opens with the Update option selected.

To open the Modify Item dialog box. To accept the changes. Youll replace it with the updated text object in the repository. The item has been updated.

66

Crystal Reports XI: Advanced

Delete items from the repository


Explanation After adding an item from the repository to a report, you can delete the instance of that item on the report by selecting it and pressing Delete. The instance will be removed, but the item will still be stored in the repository. To delete an item from the repository, select the item in Repository Explorer and press Delete. This will remove it from the repository but not from any reports that contain an instance of the item. You need to have adequate database permissions to delete objects from the repository. Do it!

A-4:

Deleting an item Heres why


To display a context menu.

Heres how
1 In the Repository Explorer, under Text Objects, right-click
Confidential

Choose Delete

A message box prompts you to indicate whether you want to delete the object. You are also warned that deleting repository objects cannot be undone and will affect the behavior of dependent objects. To delete the text object from the repository. The Confidential Report item is still there, even though it has been removed from the repository.

Click Yes 2 Observe the Page Footer section 3 Update and close the report In the Repository Explorer toolbar, click Close the Repository Explorer

To log off the Business Objects Enterprise server.

Data management features

67

Topic B: The Workbench


Explanation A new feature in Crystal Reports XI is the Workbench. The Workbench offers a way to access reports by organizing them into projects or folders that you specify. For example, you might want to organize reports by author, or by purpose, such as year-end sales reports. Once projects are added to the Workbench, you can access them easily without having to use the Start Page or the File menu.

Adding projects to the Workbench


To use the Workbench, you must first add projects to it. You then add reports to the project folders. To add projects to the Workbench: 1 Choose View, Workbench to open the Workbench. 2 Right-click the <Create a new project> icon and choose Add New Project. 3 Type a name for your project and press Enter. 4 Right-click the new folder and choose Add, Add Existing Report from the context menu. 5 In the Open dialog box, navigate to the report you wish to add. 6 Click Open.

68
Do it!

Crystal Reports XI: Advanced

B-1:

Creating a new project in the Workbench Heres why


To open the Workbench. To display a context menu.

Heres how
1 Choose View, Workbench 2 Right-click
<Create a new project>

Select the indicated option

To create a new project folder. A new folder appears with the title Untitled Project.

3 Type My projects Press e 4 Verify that My projects is selected Right-click My projects


Tell students that they can also add projects and reports by using the Add command on the Workbench toolbar.

To rename the folder. To commit the name change. Youll add a report to the project folder.

To display a context menu. To display the Open dialog box.

Choose Add,
Add Existing Report

5 Navigate to the current unit folder Select My repository report.rpt

If necessary.

Students can also doubleclick the report to add it to the folder.

Click Open

To add the report to the project folder.

6 In the Workbench, double-click


My repository report.rpt

To open the report. You can add other reports to the project folder at any time.

Close the report In the Workbench, click


To close the Workbench.

Data management features

69

Unit summary: Data management features


Topic C Topic D In this topic, you learned about the repository, a central location for storing report objects. You learned how to add, modify, use, and delete objects in the repository. In this topic, you learned how to create new project folders using the Workbench, and how to add reports to your project folders.

Independent practice activity


In this activity, youll practice adding an item to the repository. Youll also practice modifying, using, and deleting repository objects. Finally, youll create a new project folder in the Workbench, and add a report to the new project. 1 Open Repository practice. 2 Save the report as My repository practice. 3 Add the copyright text object located in the Page Footer section to the repository under Text Objects. 4 Name the text object as Outlander Copyright, and the author as Outlander Spices. Under description, type Copyright information. 5 Modify the copyright text object in the report to read Copyright 2006-2007. 6 Update the Outlander Copyright text object in the repository with the modified text object in the report. 7 Delete the copyright text object in the report and replace it with the updated Outlander Copyright text object from the repository. 8 Delete the Outlander Copyright text object from the repository, log off the server, and close the Repository Explorer. 9 Close the Repository Explorer; update and close My repository practice. 10 Open the Workbench. 11 Create a new project named Practice project, and add My repository practice to it. Open My repository practice from the Workbench. 12 Update and close the report, and close the Workbench.

610

Crystal Reports XI: Advanced

Review questions
1 What is the purpose of the Business Objects Enterprise Repository?
To provide a central location for storing a variety of files and objects that can be used in multiple reports without having to be recreated for each use

2 True or false: Anyone who has Crystal Reports on his or her computer can add an item to the Repository.
False. To add an item to the Repository, you must be given access privileges.

3 Before you can modify a Repository item, you must __________ the Repository.
disconnect it from

4 True or false: after you modify an item in the Repository, youll need to manually update each report in which that item appears.
False. Crystal Reports automatically updates the item in all instances.

5 True or false: When you delete an item from the Repository, it will automatically be deleted from any report in which it appears.
False.

6 The Workbench is a new feature that helps you to:


Manage multiple report projects

71

Unit 7 Advanced data access techniques


Unit time: 95 minutes Complete this unit, youll know how to:
A Access data from different types of data

sources by using ODBC.


B Create SQL queries by using the Database

Expert, and use queries to create reports.

72

Crystal Reports XI: Advanced

Topic A: ODBC data sources


Explanation Crystal Reports can use data from various sources, such as database files, Open Database Connectivity (ODBC) data, and Online Analytical Processing (OLAP) data to create reports. ODBC is a standard developed by Microsoft. With the ODBC standard, you can access data stored in various sources, such as Microsoft SQL Server, FoxPro, dBase, and Microsoft Excel, from a single application using the same interface. You can use ODBC without actually knowing how data is stored.

Introducing ODBC data sources


ODBC helps you easily switch from an old data source to a new data source provided the format of information stored in the new source is the same as for the old source. This is useful if an organization switches to a different Relational Database Management System (RDBMS). The ODBC standard uses an ODBC data source object to connect to a specific type of database. A data source object contains information about the database, and the particular driver to be used to access data. An application such as Crystal Reports communicates with a variety of databases using ODBC drivers for the corresponding databases. A database driver is software that contains information about the type of database and the method used to connect to it. These drivers are in the ODBC translation layer, which facilitates communication with the database. Crystal Reports uses the following process to access data by using ODBC: 1 A request for data is sent to the ODBC data source object. The ODBC translation layer converts the request into a form that can be understood by ODBC, which then sends it to the appropriate data source object. 2 The ODBC data source object passes the request to the database driver. 3 The database driver converts the data request into a form that the database understands and sends the request to the database. 4 The database then returns the data to the database driver. The driver returns this data to the data source object. 5 The report retrieves the data provided by the data source and displays it. Accessing data by using ODBC is often a slow process because the data has to pass through several layers before being displayed. This disadvantage is offset by the ability of ODBC to access data from a variety of sources.

Advanced data access techniques Do it!

73

A-1:

Discussing ODBC data sources

Questions and answers


1 What standard would you use to combine data from different sources in a report?
ODBC or Open Database Connectivity

2 What kind of software contains information about the type of database and the method used to connect to it?
A database driver

3 Where is the information about a databases location and driver stored?


In an ODBC data source

4 Name two sources of data to which you can connect using ODBC data sources.
Answers may include:

SQL Server FoxPro dBase Microsoft Excel

74

Crystal Reports XI: Advanced

Using ODBC data sources


Explanation To access data from an ODBC data source, you need to specify certain settings in the ODBC Data Source Administrator. To do this, choose Start, Control Panel, Performance and Maintenance, Administrative Tools, Data Sources (ODBC). The ODBC Data Source Administrator dialog box appears, as shown in Exhibit 7-1. A list of user data sources appears under the User DSN tab. User data sources are available only to the present user. The second tab, System DSN, lists the data sources available to all users of the computer. You can use an existing data source or add a new data source by using the Create New Data Source dialog box. To make the settings: 1 Open the ODBC Data Source Administrator dialog box. 2 Select the appropriate data source and database driver. 3 Assign a name to the data source and associate the data source with a specific database file.

Exhibit 7-1: The ODBC Data Source Administrator dialog box

Advanced data access techniques Do it!

75

A-2:

Making ODBC source settings Heres why


To open the Control Panel.

Heres how
Tell students they want a report of sales by different retailers. The retailer database is in Microsoft Access, but the sales report from the retailers is in a Microsoft Excel worksheet. They need to make settings that will specify the Retailer_sales.xls file as an ODBC source.

1 Choose Start, Control Panel Click Performance and Maintenance, and then click
Administrative Tools

Double-click
Data Sources (ODBC)

To open the ODBC Data Source Administrator dialog box.

Verify that the User DSN tab is activated 2 Click Add 3 Under Name, scroll down and select Microsoft Excel Driver (*.xls), as indicated
This is the driver Crystal Reports will use to extract data from the data source, which is an Excel file. To open the Create New Data Source dialog box.

Click Finish 4 In the Data Source Name box, type Product Information Click Select Workbook
Help students navigate to the file.

The ODBC Microsoft Excel Setup dialog box appears. This will be the name of your data source.

The Select Workbook dialog box appears. Product Sales.xls is stored in the current unit folder. To return to the ODBC Microsoft Excel Setup dialog box. To return to the ODBC Data Source Administrator dialog box. Product Information is now listed as a data source in the list. To finalize the settings.

Specify the path for the Product Sales.xls file Click OK 5 Click OK

6 Click OK Close the Administrative Tools window

76

Crystal Reports XI: Advanced

Using ODBC source to create reports


Explanation After you have made the required settings, you can use the ODBC source to create new reports. You can simultaneously use data from an ODBC source and another source, such as an Access database, to create a report. The two data sources should have some common field on which they can be linked to obtain meaningful information. You have to create a new connection to connect to the additional data source. After this, youll select the data source for which you made settings in the previous activity from the Data Source Name list. To create a report by using an ODBC source and another data source: 1 Start creating a report by clicking the Standard Report Wizard on the Start Page. 2 On the Data screen, create a new connection and specify the ODBC source and the other data source. 3 Select the ODBC source and the other data source. 4 Ensure that data is linked properly between the database file and the ODBC source. 5 Select the fields to be displayed in the report. 6 Keep clicking Next until you reach the template page where you click Finish to create the report. 7 Save the report. After you select the Standard Report Wizard option on the Start Page, the Standard Report Creation dialog box appears with Current Connections selected by default, as shown in Exhibit 7-2. Youll create a new connection as the ODBC data source has not yet been connected to any report.

Exhibit 7-2: The Standard Report Creation Wizard dialog box

Advanced data access techniques

77

Exhibit 7-3: The report created in the activity Do it!

A-3:

Creating a report by using an ODBC data source and an Access database Heres why
Youll create a new report by using a Microsoft Access database and an ODBC data source for Microsoft Excel, for which you made settings in the previous activity.

Heres how
1 On the Start Page, choose the Standard Report Wizard

2 On the Data page under Available Data Sources, expand Create New Connection, as shown
(If necessary.) The Create New Connection tree expands.

Expand Database Files


Have students verify that the Look in dialog box points to the current unit folder.

The Open dialog box appears. Retailerdatabase is located in the current unit folder.

Select Retailerdatabase and click Open 3 On the Data screen under Available Data Sources, scroll down to ODBC (RDO) and expand it, as shown

The ODBC (RDO) dialog box opens.

4 In the Data Source Name list, select Product Information Click Next Click Finish

To select the data source you created in the previous activity. The Connection Information screen appears. Logon credentials arent necessary here.

78

Crystal Reports XI: Advanced 5 Observe that Product_Sales appears under Product Information

(Youll use Product_Sales to add data to the report.) Product_Sales is the name of the table under the Excel data source, Product Information.
Tell students to scroll up if necessary.

6 In the Database Files folder, under Retailerdatabase.mdb, expand the Tables icon and select Retailers Click
To add the Retailers table to Selected Tables.

In the ODBC (RDO) folder, under Retailer Information, select Product_Sales Click 7 Click Next Observe the Link
To add the Product_Sales table to Selected Tables. The Link page appears.

The two data sources are linked by the common field, Retailer_code.

Click Next

The Fields page appears.

8 From Product_Sales, move Product ID to the Fields to Display list Expand the Retailers table From the Retailers table, move the Retailer_Code, Retailer Name, and State fields to the Fields to Display list
If necessary.

After moving the four fields, the Fields to Display list should look like this.

Click Next

The Group page appears. You can use the Group page to group the information in your report; however, it is optional.

Advanced data access techniques 9 Click Next

79

The Record Selection page appears. You can use this page to display a subset of information, which is optional. The Template page appears. On this page, you can select from a list of predefined templates. To create a report without using a template.

10 Click Next Verify that the No Template option is selected 11 Click Finish

To create the report. A warning message appears. The report contains fields from two data sources. If you create a report from different data sources, you cannot add SQL parameters in the report. (To close the box.) The report is created, as shown in Exhibit 7-3.

12 Click OK 13 Save the report as My ODBC


report

Close the report

710

Crystal Reports XI: Advanced

Topic B: SQL and the Database Expert


Explanation You can use Structured Query Language (SQL) to create queries for retrieving data from different tables based on a particular condition. A query is a statement that retrieves data from one or more database tables. To create queries in Crystal Reports, you use commands. Commands are virtual tables just like queries, created with the Database Expert. After a command is created, it can be regarded as an object and is frequently referred to as a command object. A virtual table does not actually contain the data itself, but picks data from the tables on which it is based.

SQL Syntax
SQL (often pronounced sequel) is a query language used to organize, manage, and query large relational databases. SQL syntax is based on statements, which are used to perform database operations, such as adding tables or retrieving data. The steps of a SQL statement are called clauses. Each clause in a SQL statement, except for the final one, ends with a comma (,). There are four types of clauses, as described in the following sections. SELECT clauses A SELECT clause specifies the fields to be retrieved from a table. The clause consists of the word SELECT followed by a list of fields. If youre using multiple tables in the query, each field name must be prefixed by the table name and a period. If a query is based on a single table, then the table name and period are optional. The syntax for a SELECT clause is:
SELECT <tablename>.<field 1>,<tablename>.<field 2>.... <tablename>.<field n>

SQL is a highly complex subject in itself. Tell students this is just a broad overview.

The field names in the syntax are always enclosed within grave accents (`). The grave accent key is located just below the Esc key on the keyboard. FROM clauses A FROM clause specifies names of tables from which data will be queried. In this kind of clause, the word FROM is followed by a list of all the tables whose fields were listed in the SELECT clause. You must specify the FROM clause after the SELECT clause, or else the query cannot retrieve data. The syntax is as follows:
FROM <tablename>

If there is a space in the table name, then you must enclose the full name within grave accents (`), and then follow it with a table name in which underscores (_) replace the space. For example, consider the following query:
SELECT Retailers_Table.`Retailer Code`, Retailers_Table.`Retailer Name`, Retailers_Table.`Sales` FROM `Retailers_Table`

This statement will retrieve data from the Retailer Code, Retailer Name, and Sales fields in the table named Retailers Table.

Advanced data access techniques WHERE clauses

711

A WHERE clause specifies the records or rows that will be retrieved from the table. In this clause, the word WHERE is followed by a condition, based on which the specific records should be retrieved from the table. You use comparison operators, such as equals (=), less than (<), or greater than (>), to specify a condition. The syntax is as follows:
WHERE <condition>

For example:
SELECT Retailers_Table.`Retailer Code`, Retailers_Table.`Retailer Name`, Retailers_Table.`Sales` FROM `Retailers_Table` WHERE Retailers_Table.`Sales` > 10000

This query would return the specified fields for all records in which the value of the Sales field is greater than 10,000. ORDER BY clauses An ORDER BY clause sorts the records by the values in a specific field after they have been retrieved from the database. In this clause, the words ORDER BY are followed by a field name and the sort order, which can be ascending or descending. The syntax is as follows:
ORDER BY <field> <order>

You can use the keyword ASC to specify ascending order, or DESC to specify descending order. For example, consider this query:
SELECT Retailers_Table.`Retailer Code`, Retailers_Table.`Retailer Name`, Retailers_Table.`Sales` FROM `Retailers_Table` WHERE Retailers_Table.`Sales` > 10000 ORDER BY Retailers_Table.`Retailer Name` ASC

This query is the same as in the preceding example, except that the returned data will be sorted in ascending, or alphabetical, order based on the field Retailer Name. Every SQL statement must contain both SELECT and FROM clauses. The WHERE and ORDER BY clauses are optional. Do it!

B-1:

Understanding SQL syntax

Questions and answers


1 What are the steps of a SQL statement called?
Clauses

2 In which clause do you specify the condition on which the records in a SQL query are evaluated?
WHERE

3 What are the two essential clauses in SQL queries?


SELECT and FROM

712

Crystal Reports XI: Advanced

Command objects
Explanation Command objects can be regarded as SQL queries that can be stored and used to create reports. After you create a command object, you can use it just like any other table to create reports. You can store the command object in the repository where other users can access it to create their reports. Command objects are referred to as commands. You can create a command using the Database Expert. After you create the command and add it to the repository, you can use it to create reports. You can also create a command while creating a new report. To create a command while simultaneously creating a report: 1 Create the report by using a Report Wizard. 2 Create a new connection to the required data source. 3 Double-click on the Add command appearing under the selected data source. 4 Write the SQL query in the Add Command To Report dialog box, as shown in Exhibit 7-4, to create the command. 5 Add the fields you want to display, from the command. 6 If you want to group the data or select records, choose those options on the following screens. Otherwise, keep clicking Next, until you reach the Template page, where you click Finish.

Exhibit 7-4: The SQL query typed in the Add Command To Report dialog box

Advanced data access techniques Do it!

713

B-2:

Creating a command while creating a report Heres why


The Data screen appears.

Heres how
Tell students the sales manager wants to view combined data from the Customers and Orders tables, and they will create a command and a report based on that command.

1 On the Start Page, choose Standard Report Wizard 2 Under Available Data Sources, expand Create New Connection 3 Under Database Files, expand the tables under Retailerdatabase 4 Double-click Add Command

If necessary.

If necessary. Youll create the command based on the tables Customers and Orders. The Add Command to Report dialog box appears. Youll write the SQL query here.

Tell students they can also use the text file, command_query.txt, to copy and paste the query.

5 Type the query as shown in Exhibit 7-4 Click OK Observe that under Selected Tables, Command appears, as shown
To close the Add Command to Report dialog box.

6 Click Next Observe that the fields based on the SQL query are displayed under Command, as shown

The Fields page appears.

7 Click Click Next

To add all the fields to your report. The Grouping page appears. In this activity, you do not need to make any choices about grouping. The Record Selection page appears. This page is optional. The Template page appears. Verify that No Template is selected. To create the report.

8 Click Next Click Next 9 Click Finish 10 Save the report as


My command report

714

Crystal Reports XI: Advanced

Modify command objects


Explanation After you have created a command, you can use the Database Expert to edit the command object. You can change the name of the command object and edit the SQL query associated with it. Any new report created with the modified command reflects these changes. When you click the Database Expert button, the Database Expert dialog box appears, as shown in Exhibit 7-5. To edit a command: 1 Open Database Expert. 2 Modify the command by choosing the Edit Command from the context menu. 3 Make changes to the command in the Modify Command dialog box.

Exhibit 7-5: The Database Expert dialog box

Exhibit 7-6: The report created with the modified command

Advanced data access techniques Do it!

715

B-3:

Editing a command Heres why

Heres how
1 In the Field Explorer, expand Database Fields to observe Command, as shown

2 Right-click Command Choose Database Expert 3 Under Selected Tables, select Command, as indicated

To display a context menu. Notice that here Command is the default name of the command. To open the Database Expert dialog box, as shown in Exhibit 7-5.

Youll change the name of Command to better reflect its contents.

Press F2
Tell students spaces are not allowed in the Command name.

(F2 puts the object in edit mode.) To edit the command name. To commit the name change.

Edit the name to read


Customer_Sales

and press e 4 Right-click Customer_Sales Choose Edit Command


A context menu appears. (The Modify Command dialog box appears with the complete SQL query text selected.) Youll modify the query.

Deselect the SQL query text 5 Place the insertion point at the end of the SQL query text and edit it, as shown
(The ORDER BY statement has been added to the SQL query.) The command will now be used to order the records based on the customer code.

716

Crystal Reports XI: Advanced 6 Click OK Click OK 7 Preview the report


To apply changes. To close the Database Expert. The records are now in numerical order by customer code, as shown in Exhibit 7-6. The default order is ascending.

Update the report

Adding commands to the repository


Explanation You can add a command object to the repository to share it with other users who have the rights to access the repository. This is done by right-clicking the command and choosing Add to Repository. If you then want to make changes to the command object, you have to first disconnect it from the repository by right-clicking the command and choosing Disconnect from Repository.

Advanced data access techniques Do it!

717

B-4:

Adding a command to the repository Heres why

Heres how
1 Open the Database Expert 2 Right-click Customer_Sales Choose Add to Repository 3 Log on to the server with the Administrator user account

To display the context menu.

Type Administrator in the User name field, if necessary, and do not type a password. The Add Item dialog box opens.

4 Enter the name as Customer Sales and the author as Outlander Spices 5 Under location, right-click the root folder Choose New Folder and name it My commands Click OK 6 Observe the Selected Tables list
To close the dialog box. To display a context menu. Youll create your own folder to store the command.

The path pointing to Retailerdatabase has been replaced with Query. This is because the Customer_Sales command object is no longer on the local machine and is part of the repository.

7 Under Available Data Sources, expand the Repository folder 8 Click OK

To see that the Query has now been added to the repository. To close the Database Expert. The Query is now available to use by anyone with access to the repository.

Update and close the report

718

Crystal Reports XI: Advanced

Using queries
Explanation You can use an existing query to create a report. The query does not store the data but retrieves the data from the underlying tables on which the query is based. You can use a query just as you use tables to create reports. You need to expand Current Connections in the Data page to view the existing queries. The existing queries are listed under Views. To create a report based on an existing query: 1 Create a new report. 2 Select the query on which the report will be based. 3 Follow the steps to create a report based on a query. 4 Save the report. Do it!

B-5:

Creating a report based on an existing query Heres why


To open the Data screen of the Wizard.

Heres how
1 On the Start Page, choose the Standard Report Wizard 2 Expand Current Connections Expand Retailerdatabase Expand Views

(If necessary.) To display tables and views stored under the current data source. If necessary. (To display qryCustomerOrders. Youll create the report based on this view.) This view (or query) was created in Microsoft Access by using fields from the Customers and Orders tables. The query links the two tables on the common field, Customer_code. To move qryCustomerOrders under Selected Tables. The Fields page appears, displaying the fields available under the view qryCustomerOrders To move all the fields under qryCustomerOrders under Fields to Display. The Grouping page appears. It is optional to group the information in the report. The Record Selection page appears. This, too, is optional.

Make sure students open the Retailerdatabase from the current unit folder.

3 Click Click Next 4 Click Click Next 5 Click Next

Advanced data access techniques 6 Click Next Ensure that No Template is selected
Tell students that the query used here is slightly different from the one they created earlier.

719

The Template page appears. This page is also optional.

Click Finish 7 Save the report as


My customer orders

To create the report.

8 Close the report

720

Crystal Reports XI: Advanced

Unit summary: Advanced data access techniques


Topic A In this topic, you learned how to use ODBC data sources to access data from different types of databases simultaneously. You also learned how to use ODBC data sources to create a report. In this topic, you learned how to create commands by using the Database Expert. You also learned how to make changes to a command and add it to the repository. In addition, you learned how to create a report based on an existing query.

Topic B

Independent practice activity


In this activity, youll practice using two different data sources to create a report. Next, youll practice creating a report while creating a command, modifying the command, and adding the command to the repository. 1 Create a report by using the Orders table in Retailerdatabase and the ODBC source, which is provided to you as an Excel workbook, Retailer Sales, in the current unit folder. Make ODBC source settings. Name the data source Retail Orders. Start the Standard Report Wizard. Make a new ODBC (RDO) connection. Link the two data sources on the common field, Retailer_code. The final report should display the sales for each product ID. 2 Compare your report to Exhibit 7-7. 3 Save the report as My product sales and close it. 4 Create a report containing a command based on the tables Orders and Retailers from Retailerdatabase. The command should retrieve the fields Retailer_code and Retailer_name from the Retailers table, and the fields Order_date and Product_description from the Orders table. (You can use IPA1.txt in the current unit folder to construct the SQL query, but try to build it on your own.) 5 Save the report as My practice command report. 6 Rename the command to Retailer_sales and modify the command to sort the records by the Order_date field. (You can use IPA2.txt to modify the query, but try to modify it on your own.) 7 Format the Order_date field to read mm/dd/yyyy. Compare your report to Exhibit 7-8. 8 Add the Retailer_sales command to the repository, in a new folder called Practice commands. 9 Update and close the report. 10 Close Crystal Reports.

Advanced data access techniques

721

Exhibit 7-7: A portion of the report created after step 2 of the Independent Practice Activity

Exhibit 7-8: A portion of the report after step 7 of the Independent Practice Activity

722

Crystal Reports XI: Advanced

Review questions
1 What does the acronym ODBC stand for?
Open Database Connectivity

2 What is an advantage and a disadvantage of using an ODBC data source?


It can be a slow process due to the number of layers the data has to pass through before being displayed. However, this is offset by the wide range of data sources that can be accessed by the ODBC standard.

3 What tool do you use to select an ODBC data source and a database driver?
The ODBC Data Source Administrator

4 What does the acronym SQL stand for?


Structured Query Language

5 True or false: Every SQL must contain SELECT, FROM, and WHERE clauses.
False. The WHERE clause is optional.

6 SQL queries that are stored and used to create reports are also known as ________.
command objects

S-ar putea să vă placă și