Crystal Reports 2008 Designer 2 Workshop

©2008 Vision Harvest, Inc.

Crystal Reports 2008 Designer 2 Workshop

Vision Harvest, Inc. 888-236-8087 sales@visionharvest.com Published: July 10, 2008 Part: VISI100071S

i

Crystal Reports 2008 Designer 2 Workshop

©2008 Vision Harvest, Inc.

©2008 Vision Harvest, Inc. ALL RIGHTS RESERVED

This course covers Crystal Reports® 2008 No part of this manual may be copied, photocopied, or reproduced in any form or by any means without permission in writing from the Author - Vision Harvest, Inc. All other trademarks, service marks, products or services are trademarks or registered trademarks of their respective holders. This course and all materials supplied to the student are designed to familiarize the student with the operation of the software programs. We urge each student to review the manuals provided by the software publisher regarding specific questions as to the operation of the programs. THERE ARE NO WARRANTIES, EXPRESSED OR IMPLIED, INCLUDING WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, MADE WITH RESPECT TO THESE MATERIALS OR ANY OTHER INFORMATION PROVIDED TO THE STUDENT. ANY SIMILARITIES BETWEEN FICTITIOUS COMPANIES, THEIR DOMAIN NAMES, OR PERSONS WITH REAL COMPANIES OR PERSONS IS PURELY COINCIDENTAL AND IS NOT INTENDED TO PROMOTE, ENDORSE OR REFER TO SUCH EXISTING COMPANIES OR PERSONS. VISION HARVEST, INC. NOR ITS RESPECTIVE PRODUCTS OR SERVICES ARE AFFILIATED WITH, OR ENDORSED, LICENSED, OR SPONSORED BY BUSINESS OBJECTS, THE OWNER OF CRYSTAL REPORTS.

This courseware has been developed by the professional team at Vision Harvest, Inc., www.visionharvest.com. Questions, comments or concerns about courseware content should be sent to sales@visionharvest.com or 888.236.8087.

ii

Crystal Reports 2008 Designer 2 Workshop

©2008 Vision Harvest, Inc.

Table of Contents
Introduction ..................................................................................................................................................... 1 Introduction Objectives ..................................................................................................................... 2 About Crystal Reports ........................................................................................................................ 2 Training Philosophy ............................................................................................................................ 2 Pre-Qualification Exercise for the Designer 2 Workshop ................................................................. 3 Why Should You Pre-qualify Yourself for the Designer 2 Workshop? ................................ 3 Pre-qualification Exercise ...................................................................................................... 4 Class Objectives .................................................................................................................................. 7 About This Manual .............................................................................................................................. 8 Tips, Notes, and Warnings .................................................................................................................. 9 Lesson 1: Refresher Exercise ......................................................................................................................... 11 Lesson Objectives ............................................................................................................................. 12 Review of Planning a Report ............................................................................................................ 13 Creating the Report .......................................................................................................................... 15 Placing Fields on the Report................................................................................................ 16 Creating the Formulas ......................................................................................................... 17 Advanced Grouping ............................................................................................................. 18 Selecting Certain Records .................................................................................................... 20 Helpful Hints for Formatting the Report ......................................................................................... 21 Adding and Working with Text Objects .............................................................................. 21 Hiding and Suppressing Sections ....................................................................................... 21 Guidelines ............................................................................................................................. 21 Lesson 2: Power Formatting with Multiple Sections .................................................................................. 25 Lesson Objectives ............................................................................................................................. 26 Using Multiple Sections in Reports ................................................................................................. 27 Using the Section Expert to Work with Sections ............................................................................ 28 Conditionally Formatting Multiple Sections .................................................................................. 32 Challenge Exercise – Formatting with Multiple Sections .............................................................. 34 Challenge Exercise – Conditionally Formatting Using DrillDownGroupLevel ............................ 36

iii

Crystal Reports 2008 Designer 2 Workshop

©2008 Vision Harvest, Inc.

Challenge Exercise – Conditionally Formatting Multiple Sections ............................................... 38 Lesson 3: Using the Running Totals Feature ................................................................................................ 41 Lesson Objectives ............................................................................................................................. 42 Understanding Running Totals ........................................................................................................ 43 Creating Running Totals for a List of Numbers ............................................................................... 44 Conditional Running Totals .............................................................................................................. 48 Challenge Exercise – Creating a Conditional Running Total .......................................................... 52 Lesson 4: Prompting with Parameters ......................................................................................................... 55 Lesson Objectives ............................................................................................................................. 56 Parameter Fields Overview .............................................................................................................. 57 Parameter Field Considerations ...................................................................................................... 58 Creating a Parameter Field............................................................................................................... 58 Using a Parameter to Select Records ............................................................................................... 61 Using a Parameter Field.................................................................................................................... 62 Using the Parameter Panel ............................................................................................................... 63 Creating a Dynamic Value List for Parameter Values ..................................................................... 64 Importing a Pick List ......................................................................................................................... 64 Adding Parameter Values to Text Objects....................................................................................... 66 Allowing Multiple Values in Parameters ......................................................................................... 67 Using Multiple Parameter Fields in Reports ................................................................................... 68 Specifying and Limiting a Range for a Parameter .......................................................................... 68 Using Parameters in Conditional Formatting ................................................................................. 71 Using an Edit Mask to Limit String Parameters .............................................................................. 72 Sorting with a Parameter ................................................................................................................. 74 Group Sorting with a Parameter...................................................................................................... 75 Using a Parameter to set N in a Top N or Bottom N report ............................................................ 76 Displaying Parameter Fields ........................................................................................................... 77 Cascading Parameter Fields ............................................................................................................. 77 Challenge Exercise – Using Parameters .......................................................................................... 79 Challenge Exercise – Displaying Parameters .................................................................................. 81

iv

Crystal Reports 2008 Designer 2 Workshop

©2008 Vision Harvest, Inc.

Lesson 5: Using Advanced Formula Features .............................................................................................. 83 Lesson Objectives ............................................................................................................................ 84 Understanding How Crystal Reports Processes the Data .............................................................. 85 What Is a Pass? ...................................................................................................................... 85 Pre-Pass#1............................................................................................................................. 85 Pass #1 ................................................................................................................................... 85 Pre-Pass #2 ............................................................................................................................ 86 Pass #2 ................................................................................................................................... 86 Pass #3 ................................................................................................................................... 87 Using Evaluation Time Functions ........................................................................................ 87 Working with Variables ........................................................................................................ 88 Declaring a Variable ............................................................................................................. 88 Assigning a Value to a Variable ........................................................................................... 89 Using a Variable in a Formula .............................................................................................. 89 Variable Scope ...................................................................................................................... 90 Separating Statements in Complex Formulas ................................................................... 91 Working with Arrays ........................................................................................................................ 95 Understanding the Formula Evaluation Time Debugger .............................................................. 98 Challenge Exercise – Understand and Set Up the YTD Comparison Report...............................100 Lesson 6: Using Subreporting as a Workaround Solution........................................................................107 Lesson Objectives ...........................................................................................................................108 Understanding Subreports ............................................................................................................109 Unlinked versus Linked Subreports ..............................................................................................109 Creating an Unlinked Subreport ...................................................................................................109 Linking a Subreport .......................................................................................................................111 Database Links versus Subreports in One-to-Many Situations ..................................................112 Formatting the Subreport ..............................................................................................................114 Passing Data from the Main Report into a Subreport ..................................................................115 Creating On-Demand Subreports..................................................................................................118 Creating Hyperlinks ........................................................................................................................119 Using Subreports to Link “Unlinkable” Data ................................................................................120 Challenge Exercise – Creating Reports with Linked Subreports .................................................121

v

Crystal Reports 2008 Designer 2 Workshop

©2008 Vision Harvest, Inc.

Lesson 7: Creating Powerful Groups ..........................................................................................................125 Lesson Objectives ...........................................................................................................................126 Creating Custom Groups ................................................................................................................127 Customizing Group Sort Order ......................................................................................................131 Using Group Selection to Filter the Records in the Report ..........................................................133 Grouping on a Formula Field .........................................................................................................134 Grouping Hierarchically .................................................................................................................136 Challenge Exercise – Create Customized Grouping .....................................................................140 Challenge Exercise - Using Group Selection .................................................................................141 Challenge Exercise - Creating a Group Using a Formula ..............................................................142 Lesson 8: Working with Cross-Tab Reports ................................................................................................145 Lesson Objectives ...........................................................................................................................146 Understanding How Cross-Tabs Affect Your Data ........................................................................147 Creating a Cross-Tab Report ........................................................................................................149 Creating a Cross-Tab with Multiple Rows or Columns..................................................................153 Applying a Formatting Style to the Cross-Tab ..............................................................................154 Customizing the Cross-Tab Format ...............................................................................................156 Changing Background Colors............................................................................................156 Formatting Individual Cells ...............................................................................................157 Changing the Summary Operation ............................................................................................... 158 Suppressing Rows, Columns or Totals ..............................................................................158 Repeating Row Heading for Multi-Page Cross-Tabs ........................................................160 Using Alias Names for Column and Row Headings ..........................................................160 Charting Cross-Tabs ........................................................................................................................162 Customizing Cross-Tab Group Names ..........................................................................................164 CurrentFieldValue ...........................................................................................................................166 Challenge Exercise – Cross-Tab Reports ........................................................................................ 168 Lesson 9: Report Alerts ...............................................................................................................................173 Lesson Objectives ...........................................................................................................................174 What are Report Alerts ...................................................................................................................175 Creating Report Alerts ....................................................................................................................176 Basing Report Formulas or Conditional Formatting on Report Alerts ......................................178 Creative Usage for Report Alerts ..................................................................................................180
vi

Crystal Reports 2008 Designer 2 Workshop

©2008 Vision Harvest, Inc.

Appendix A: Report Templates ...................................................................................................................185 Lesson Objectives ...........................................................................................................................186 What is a Report Template .............................................................................................................187 Standard Report Creation Wizard and Templates .......................................................................187 The Template Expert .......................................................................................................................190 Applying a Template and the consequences ................................................................................190 Template Considerations ...............................................................................................................195 Creating Your Own Templates ........................................................................................................196 Inserting Template Fields ..................................................................................................196 Formatting Template Fields ...............................................................................................197 Giving Template Fields a Value..........................................................................................197 Appendix B: The Northwind 2008 Database .............................................................................................203 Appendix C: Installation and System Requirements ................................................................................207 Installing the Application ...............................................................................................................208 Minimum Installation Requirements ............................................................................................208 Appendix D: Setup Instructions for Crystal Reports 2008 .......................................................................211 Crystal Reports 2008 Application installation Instructions ........................................................212 Installing Required Class Files .......................................................................................................215 Appendix E: Function and Operator Locations .........................................................................................217 Appendix F: Glossary ..................................................................................................................................231

vii

Crystal Reports 2008 Designer 2 Workshop

©2008 Vision Harvest, Inc.

viii

Crystal Reports 2008 Designer 2 Workshop Introduction

©2008 Vision Harvest, Inc.

Introduction

1

Crystal Reports 2008 Designer 2 Workshop Introduction

©2008 Vision Harvest, Inc.

Introduction Objectives
This manual is written to give you a step-by-step guide for your classroom training and a handy reference for your daily work. In this Introduction, you will learn how to use this training guide effectively. This section covers the following topics: An introduction to the Crystal Reports application Pre-Qualification Exercise Class objectives Help with using this training guide Information on how to start the program

About Crystal Reports
In today’s information intensive environment, every business has a database of some sort. After all, business today is all about information and databases give you a handle on the massive amounts of information you must deal with. Therefore, your business has a database and from that database, you need reports. The problem is, most reporting capabilities that come with database programs are limited. They only report on data from that program. Many users need to report on data from multiple sources, even databases such as Oracle, Microsoft SQL Server, DB2 or Sybase. Crystal Reports is one of the most powerful reporting programs available with the ability to pull data from all types of data sources. You can use Crystal Reports to generate reports from any of the standard PC database programs; Access, Paradox, or FoxPro, as well as from a mainframe or server database. Crystal also has a powerful web-reporting server that allows you to distribute your reports over the web. Crystal Reports is bundled with more than 160 other programs including Visual Basic, some medical applications, many accounting packages and several ERP solutions. It makes report generation easy without requiring you to be a programmer or a database expert. If you know how to work in a Windows environment and are familiar with the data you want to use, you can create a Crystal Report that looks professional and makes sense.

Training Philosophy
Studies show that people retain 10% of information they see, 20% of information they hear, 50% of what they see and hear, and 80% of what they see, hear and do. In line with this concept, the class utilizes a hands-on method of training. You will see the effects of new procedures on the screen, hear the instructor explain how and why to use features, and perform the actions yourself as you learn. In addition, this class focuses on your ability to perform tasks using the most productive techniques. The manual may contain several methods of accomplishing a certain task. However, class time does not allow for practice of all methods for each task. Your instructor will guide you in the most effective method of performing a task, but inform you of other methods that are available. Questions are encouraged. While we give our best effort to explain new concepts in understandable terms, you may need to hear the concept again or have it explained more thoroughly. Please let the instructor know when you need more information!
2

Crystal Reports 2008 Designer 2 Workshop Introduction

©2008 Vision Harvest, Inc.

Pre-Qualification Exercise for the Designer 2 Workshop
Why Should You Pre-qualify Yourself for the Designer 2 Workshop?
The Crystal Reports 2008 Designer 2 Workshop is designed for the experienced Crystal Reports user. It covers the more complex and powerful features of the program. The class discusses very technical issues and includes several fast-paced, comprehensive exercises. Our instructors have years of experience helping students to get the most out of their training. However, it is not always possible in a high level workshop to assist students with basic tasks. In order to maximize the benefit you receive from the Crystal Reports 2008 Designer 2 Workshop, you should come into the training with a certain skill level. We assume all students who sign up for this workshop have a comfortable level of understanding in regards to relational databases. Students should also be able to perform the following tasks in Crystal Reports: Create a new report, insert fields, save the report and refresh the data. Add multiple tables to the report using the Data Explorer. Use the select expert to pull only the data needed from the database. Insert groups and summarize fields within the group. Perform formatting tasks. Create, save and use formulas in the report. If you would like to evaluate for yourself whether this is the correct level course, take our self-evaluation exercise. The exercise consists of writing a report in Crystal Reports. When you are finished, compare your report to the one our experts have done to see how well you understand the basic features of Crystal Reports. You can obtain the exercise and the results report from the Designer 1 Workshop class files. If you have trouble creating the report or getting the correct results, or if you cannot perform some of the above-mentioned tasks, then we strongly recommend that you take the Crystal Reports 2008 Designer 1 Workshop before attending the Designer 2 Workshop. By assuring you are well prepared for the Designer 2 Workshop, you maximize the benefits you receive from this in-depth look at advanced report writing.

3

Crystal Reports 2008 Designer 2 Workshop Introduction Pre-qualification Exercise

©2008 Vision Harvest, Inc.

Using the Northwind 2008 database available included with the class files, create a report invoicing customers for each order. The report needs to show the customer billing address, the Invoice#, the sales person, the order date, the requested date, the ship date and the company shipping the order. The Details section should list the product ID, the product name, product category, the unit price, the quantity, and the line item total. Select only those orders with an ship date between January 1, 2008 and March 31, 2008. Group on the CustomerID, then on the OrderID. Display each order on its own page. Sum the line item total amount for each OrderID. Calculate the sales tax for the order at 6% and total the subtotal and sales tax. You will need to pull data from the following tables: Customers Orders Employees Shippers Products OrderDetails Categories

The tables joins should look like the example below, but Smart Linking might link incorectly, so double check.

4

Crystal Reports 2008 Designer 2 Workshop Introduction
You will need to create the following formulas:

©2008 Vision Harvest, Inc.

Line Item Total that multiplies the unit price times the quantity for each product ordered Sales Tax that multiplies the sum of each line item total times 6% Order Total that adds the sum of each line item total and the sales tax You will need to create the following text boxes: О О О О An address box with the text To: then the company name, the address, the city, region, postal code and country An employee box with the employee first name, a space, then the last name An invoce box with invoice date An order information box containg the order date, required date, shpped date and shipped via fields

Format the report to look like the following:

5

Crystal Reports 2008 Designer 2 Workshop Introduction
The Design view should look similar to the following example:

©2008 Vision Harvest, Inc.

6

Crystal Reports 2008 Designer 2 Workshop Introduction

©2008 Vision Harvest, Inc.

Class Objectives
This class is a performance based instructional system. It is geared to provide you with the tools you need to build and distribute reports the quickest, most efficient way. After completing this course, you will be able to perform the following tasks: Review Designer 1 with the Refresher Exercise Use multiple sections in reports for advanced formatting techniques Underlay graphics and charts to print beside data Calculate running totals in reports Develop parameter fields to prompt users for information Limit user entry into parameter fields Understand Crystal Reports data handling and Evaluation Time functions Comfortably make use of variables in formulas Work with arrays and control structures in formulas for more flexible decision making Use additional reports within a main report as subreports Create linked subreports to tie data from another report to the current report Format subreports to display on demand only Customize groups in the report with formulas and custom names and create hierarchical groups Perform group selection based on summary field values Create and format Cross-Tab reports and create charts from Cross-Tabs Work with Report Alerts Create and use Report Templates Solve table linking problems with advanced linking techniques

7

Crystal Reports 2008 Designer 2 Workshop Introduction

©2008 Vision Harvest, Inc.

About This Manual
Each section of this manual contains objectives to provide you with the overall goals for the lesson. Lessons have descriptions of features and concepts followed by systematic directions for completing a specific task. Each section ends with a challenge exercise to help you practice the skills you learned in the lesson. Challenge exercises provide you with tasks to accomplish. Try to complete these exercises on your own. As you work in this Training Guide, certain conventions are used to identify specific procedures. Use the following table as a guide:

Training Guide Conventions
Item Menu Commands Illustrated As Underlined letters for accessing menu commands are shown: Example: File/Open Command Buttons in dialog boxes are shown as buttons:

Command Buttons

Example: Categories, Radio Buttons, All options within dialog boxes are listed in italicized text: Text Boxes, Check Boxes Example: the Keep Group Together check box the Other radio button Keystrokes Keyboard keys are indicated by uppercase text: Example: press ENTER Keyboard combinations are shown in uppercase text with a plus sign (+) between the keys that need to be pressed simultaneously. Example: press CTRL + S to save Toolbar buttons are indicated by the button name and a graphic image of the button: button Example: click the Print Preview Text to be typed or file names to be selected are printed in bold letters: Example: type Henry select grouping.rpt Step-by-Step exercises in the text are indicated by bold text and the For example:

Toolbar Buttons

Typing or File Selections

Exercises

symbol.

Exercise - Format Objects

8

Crystal Reports 2008 Designer 2 Workshop Introduction

©2008 Vision Harvest, Inc.

Tips, Notes, and Warnings
Tips, notes and warnings display with the following icons. Text for these additional comments display in bold and italics as shown below:

This icon indicates a tip or shortcut.

This icon points out a note of additional information.

This icon calls attention to a warning or very important note

9

Crystal Reports 2008 Designer 2 Workshop Introduction

©2008 Vision Harvest, Inc.

NOTES

10

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise

©2008 Vision Harvest, Inc.

Lesson 1 Refresher Exercise

11

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise

©2008 Vision Harvest, Inc.

Lesson Objectives
After completing this lesson, you will be able to: Plan and Create a report from a set of business requirements Review the techniques needed to plan and create a report Add multiple groups to reports Create groups within groups to subdivide your reports how you want Summarize different group levels You can effectively summarize information at any group level or all group levels Insert simple lines and boxes for formatting Make reports professional and attractive with graphical features Utilize the Repeated Group Header feature Add a “Continued…” message when a group prints across pages

12

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise

©2008 Vision Harvest, Inc.

Review of Planning a Report
To make the report creation process efficient, you must plan the report. A little work up front before you ever open Crystal Reports can save a lot of time putting the report together. It can also save problems caused by adding incorrect tables to the report, which can affect the accuracy of the records displayed. You must look at the business requirements for the report and decide what fields you need and the tables in which they are located. It is also helpful to look at things such as groupings, whether you need Cross-Tabs, fields needed for formulas and selection criteria. Suppose someone asks you to create a report based on the Northwind 2008 database. Below are the business requirements for the report: The person requesting the report needs to see by Supplier and Category Name the monthly sales totals. They want the Order ID, the Product Name, the line item Unit Price and Quantity and a total for each line item. They want the sales amounts summarized for each supplier, category name and month. They only need to see sales for 2007. Some of the groups are large enough to display on more than one page. They want the Supplier Name and Category Name repeated at the top of each page. If the Category Name group continues from the previous page, they want the word “Continued…” to print. The person requesting the report has supplied you with a printout of what the report should look like. See the sample on the next page.

13

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise

©2008 Vision Harvest, Inc.

To create this report, first determine which fields you need. For the Detail section, you need the OrderID field, ProductName field, the UnitPrice field and the Quantity field For the Line Total formula, you need to multiply the UnitPrice field and the Quantity field For grouping, you need the SupplierName, the CategoryName, and the OrderDate fields Finally, you need to select orders from 2007 based on the OrderDate field Next, decide which tables you need to add to get the required fields. The SupplierName field is in the Suppliers table The ProductName field is in the Products table The OrderID and OrderDate fields are in Orders table The UnitPrice and Quantity fields are in OrderDetails table The CategoryName field is in the Categories table

14

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise

©2008 Vision Harvest, Inc.

The order in which the tables are linked is usually very important from a performance viewpoint. When using the Smart Linking feature provided by Crystal Reports, the tables will be linked automatically in the most logical performance-driven fashion, but this is only true in Crystal Reports 2008. Crystal Reports 2008 attempts to link tables together where the “To” table contains a primary key (indexed, no duplicates). The reason is to improve database performance and in most instances is the best choice to reduce database querying time. In some cases this is not the best choice and it is fairly easy to overide the automatic links and create your own. This means you can simply add the tables in any order and let the Smart Linking feature do the rest of the work.

Creating the Report
Since you have given this some thought and determined the required tables, it is time to create the report. Once the tables are added, Smart Linking will create the links (joins) similar to the following example:

Remember you can add multiple tables to a report from the Database Expert. You work with links using the Links tab on the Database Expert. The Database Expert is accessed under the Database menu or by selecting the Database Expert button on the Experts toolbar.

15

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise Placing Fields on the Report

©2008 Vision Harvest, Inc.

Remember you have three ways of placing fields on a report. Select the field in the Field Explorer, then: Click the Insert button, and then click in the report Drag the field to the report Right mouse click, choose Insert to Report from the short cut menu, and then click in the report When you place a field in the Details section, Crystal Reports adds a detail field title in the Page Header section and aligns the field and field title with a guideline. You can drag the guideline marker in the ruler to move the field and its title together. Now that you have planned the report, you are ready to use Crystal Reports to create the report.

Exercise 1.0 - Begin the Monthly Sales by Supplier and Category Report and Link the Tables Needed
1. Start a new report as a blank report. Open the Create New Connection folder then open the Access/Excel (DAO) folder. The Access/Excel (DAO) dialog opens. Make sure the Database Type: is set to Access and the Database Name: text box points to the Northwind 2008.mdb database found in the CR2008 Class Resources\Databases\ Northwind 2008.mdb from Class Resource Files provided with this workshop Add the tables indicated by the business requirements. (Categories, OrderDetails, Orders, Products and Suppliers) The Auto-Link feature should link the tables automatically. Clear the links and do them yourself, but create the links to match the example on the previous page. Add the appropriate fields to the Details section (Orders.OrderID, Products.ProductName, OrderDetails.UnitPrice, OrderDetails.Quantity) Resize the ProductName field to be approx. 2.5 inches in width Change the Printer Setup to a Portrait page layout, if necessary. Change the margins to be .5” on all four sides

2. 3. 4. 5. 6.

16

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise Creating the Formulas

©2008 Vision Harvest, Inc.

You are also going to need two formulas for this report. It can be helpful to write out the formulas during the planning stage to be sure you have accounted for all necessary fields. The formulas you need for this report are as follows: Formula: Line Total {OrderDetails.Quantity} * {OrderDetails.UnitPrice} Formula: Occurance If InRepeatedGroupHeader then “(Repeated Occurance)” Else “(First Occurance)” Remember formulas are created from the Field Explorer dialog box. Select Formula Fields, and then click the New button. After naming the formula, the Formula Editor dialog box opens, providing you with three lists to select fields, functions and operators.

Exercise 1.1 – Create the Formulas and add to the Report
1. 2. 3. 4. 5. Select Formula Fields: in the Field Explorer dialog box, then click the Name the formula Line Total and select OK Create the formula shown above Add the formula to the report Details section after the Quantity field Create the Occurance formula, but do not add it to the report yet You will add this formula later to display a “Continued” message in the group header. button

NOTE: The InRepeatedGroupHeader function is a function in the Print State category. Click the + sign to the left of Print State in the middle list in the Formula Editor, and then scroll to find the function. Double click the function to add it to the formula.

17

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise Advanced Grouping

©2008 Vision Harvest, Inc.

You can group data by using the Insert/Group… command or by clicking the Insert Group button on the Insert toolbar or the Group Expert button on the Experts toolbar. This report requires an OrderDate group nested inside a CategoryName group, nested inside a SupplierName group as shown in the Group Expert illustration below:

As you create groups, Crystal Reports nests each group inside the previous one you created. However, you can reorder groups in any order you want. To reorder groups, left-click the Group Header section name at the left of the Design screen for the group you want to move. The group header and footer sections are highlighted. Drag the group to the new location. The mouse pointer changes to a grabbing hand as you drag. In the Group Expert shown above you simply move the group headers using the arrows in the top right of the window

18

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise

©2008 Vision Harvest, Inc.

TIP: When you group on a date field, Crystal Reports allows you to define the period for which the date is broken down; i.e. monthly, yearly, quarterly, etc. A third drop-down list appears automatically in the Insert Group options dialog box allowing you to specify when the group is printed.

Remember you can summarize any field by RIGHT clicking it, then choosing Insert Summary… You must specify the type of calculation you want Crystal Reports to perform and the group at which you want the summary to appear.

Exercise 1.2 – Create groups and summarize the Line Total field
1. Open the Group Expert window using the Group Expert button. Create a group on the CategoryName field. Turn on the Repeat Group Header On Each Page feature by selecting the Options Tab Create a second group on the SupplierName field. Also, turn on the Repeat Group Header On Each Page feature The report requirements call for the report to display information by SupplierName and then Category, so you need to change the order of the groups. Click the Group Expert button. Select the CategoryName field in the Group By: list and then click the Down Arrow to reorder the groups The SupplierName should be the first group in the Group Expert with the CategoryName nested underneath. Create a third group on the OrderDate field. Choose to print the section for each Month. Using the Options tab check on the Keep Group Together item

2. 3.

4.

19

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise
5.

©2008 Vision Harvest, Inc.

Create a summary for the Line Total column. Do this by checking on the Add to all group levels option and then choose OK from the Insert Summary dialog All the summary fields should automatically line up on the guideline to which the field is attached.

Selecting Certain Records
Remember Crystal Reports pulls all records from the database unless you filter the records based on some criteria. The business requirements for this report requests only records from the year 2007. To specify this, use the between operator and specify all records with an order date range beginning 01/01/07 and ending 12/31/07.

Exercise 1.3 – Select records with an Order Date in 2004
1. 2. 3. 4. 5. 6. Make sure there are no fields selected on the report, and then click the Select Expert button on the Experts toolbar. Choose the OrderDate field. Choose the is between operator. In the first drop-down list, select 1/1/2007 12:00:00AM. In the second drop-down list select 12/31/2007 12:00:00AM. Click OK when finished. At this point save and preview the report. Name the report: Monthly Sales by Supplier and Category.rpt
20

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise

©2008 Vision Harvest, Inc.

Helpful Hints for Formatting the Report
Adding and Working with Text Objects
Once you have created a group, you can delete the group name field from the group header without affecting the grouping. You can delete the SupplierName and CategoryName fields from Group Headers #1 and #2, and then create a text object in each group header containing typed text and Group Name fields. Remember text objects can contain text you type and fields from the report. You can add a field to a text object by dragging the field from the Field Explorer dialog box into the text object. Once you have a field selected, the mouse pointer changes to an arrow with an object image attached. As you move the mouse pointer onto the text object, the text object will open to accept a new object. You can see when the text object is ready to accept a field (object) when the flashing insertion bar appears in the text object and the mouse no longer has an object image attached to it.

Also remember you can format all or part of a text object: To format the entire text object, select the object (there are handles around the object) then apply the formatting To format part of a text object, double click the object to enter Edit Mode, and then select the part you want to format. When the part is highlighted, apply the formatting To format a field inside a text object, double click the object to enter Edit Mode, and then click on the field. Once the field is highlighted, apply the formatting

Hiding and Suppressing Sections
Remember you can hide or suppress sections in a report by RIGHT clicking on the section name in Design view and choosing the appropriate command. Hiding a section causes the section to not display in the Preview tab. However, users can double click summaries to display hidden details. Suppressing a section causes the section to not display without any options for viewing it. A hidden or suppressed section will be grayed out in the Design tab.

Guidelines
As a reminder, you can add horizontal guidelines to the rulers at the left of each section and snap the tops or bottoms of objects to the guidelines to horizontally align them.

21

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise Exercise 1.4 - Format the Report
1. 2. Return to the Design view It is easier to add and format objects from Design view.

©2008 Vision Harvest, Inc.

Add the title and format as you see it in the sample report at the end of this exercise. Add the Northwind Traders logo (included in class files) to the right side of the Report Header Delete the Group #1 Name and Group #2 Name fields from Group Headers #1 and #2 Using the sample report as a reference, create a text box in Group Header #1. Type the text Supplier Name: then add the Group #1 Name: SupplierName field from the Group Name fields category in the Field Explorer. Format all objects in the text box to Bold. You may need to resize the text box. See the sample at the end of the exercise for final formatting

3. 4.

5.

Repeat step 4 for Group Header #2. Substitute Category: for Supplier Name:

6.

Add text boxes in Group Footers #1 and #2 to the left of the subtotals and format to be bold, right justified. Add text to reflect subtotal information with Group Name field information similar to the following:

7. 8.

Format the summary field in the Group Footer #3 section to have a top double line border Resize Group Header #3 to be .5” tall. Multi-select all field headers in the Page Header section and move them down into the available space in Group Header #3. Format the titles to bold and remove the underline. By placing the titles in this section, the titles will reprint with each month’s data. Format the OrderID field to display without a comma. Format the UnitPrice field, the Line Total formula, and all the summary fields to have a floating $, if necessary Depending on how you have the default formats set for Date/Time fields; you may need to reformat the Group #3 Name fields. The date should look like this: January 2007.

9. 10.

22

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise
11.

©2008 Vision Harvest, Inc.

From the Special Fields list, add the Page N of M field to the left side of the Page Footer. Add a text box on the right side of the page footer that reads Order information as of. Add the Data Date special field after the text. Format both items to be italicized To add the words “(Repeated Occurance)” or “(First Occurance)” for Group Headers #1 and #2 , place the Occurance formula field in both Group Header #1 and #2 text boxes. Format just the Occurance formula to be Blue in each of the text boxes Save and preview the report. Do not forget you can navigate easily through the report using the Group Tree section at the left of the screen. Just click the group you want to view. Close the report

12.

13.

The Design view of the report should be similar to the following illustration:

23

Crystal Reports 2008 Designer 2 Workshop Lesson 1: Refresher Exercise

©2008 Vision Harvest, Inc.

NOTES

24

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

Lesson 2 Power Formatting with Multiple Sections

25

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

Lesson Objectives
After completing this lesson, you will be able to: Create multiple sections Expand your formatting power by learning how to add sections to the report Underlay a section Display a graphic or chart beside the data it represents by utilizing the underlay feature Use multiple sections for conditional formatting Add additional sections that only display under certain conditions

26

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

Using Multiple Sections in Reports
By default, Crystal Reports gives you five design areas to use when building your report: Report Header, Page Header, Details, Report Footer, and Page Footer.

Each area contains only a single section when you first begin your report. There are certain reporting tasks you can perform most efficiently by creating multiple sections within an area, such as: Putting conditional messages to appear under certain conditions Formatting objects/sections differently based on field values Alternating background colors on a row-by-row basis Adding blank lines under specific conditions, such as every fifth row Managing the Underlay feature when some objects should not underlay When you understand the power of multiple sections, you discover many ways you can use them to produce the report effects you want. The following are some ideas for using multiple sections: Suppose you want to display current order amounts in the Details section. If the customer has outstanding amounts you want to display them as well. You add an additional Details section (b) and conditionally format it to display only if there are outstanding order amounts. You are printing an employee listing grouped by Employee Name. You have information on each employee, including address, telephone, start date and sales for the last month. You also have a field displaying the employee’s picture you want shown beside the printed data. You cannot put it in the Employee Name group header because it prints above the rest of the data and takes up too much space. So, you create a second group header section, put the picture there, and then turn on “Underlay Following Sections”. The picture will then print beside each employee’s data.

27

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

You need a single page summary report of the top twenty customers. Included in the report, you need a graph showing each region’s percent of total sales. There is not enough room to print the graph above or below the customer listing. You can put the graph in a Report Header b section and underlay the section, causing the graph to print along side the data. Your report prints customer invoices and a list of the orders in the last month. You want to include a nice letter to thank paid up customers for keeping their account current. For overdue customers, you want a more forceful letter asking them for payment. You can create two Group Header sections and conditionally suppress each one depending on the condition of the account. The Detail section would show all orders currently not paid, along with their due dates. These are only some ideas for using multiple sections. You are going to try some of these ideas in following exercises.

Using the Section Expert to Work with Sections
In the Section Expert, you can easily insert, merge and delete sections. You can also move sections within an area and conditionally format sections. Remember, you can open the Section Expert in three ways: Choose Report|Section Expert… Click the Section Expert button on the Experts toolbar

RIGHT click the section name you want to format, then choose Section Expert from the shortcut menu In the Section Expert, you can select the section you want to work with in the Sections: list, and then use the Insert, Delete, or Merge buttons to manipulate additional sections. The arrow buttons allow you to move sections within an area.

28

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

You can also perform all these section procedures from the Section shortcut menu. RIGHT click on the left side of the screen where you see the section name of the section you wish to change. The shortcut menu contains commands for inserting, merging and deleting sections.

WARNING: If there is currently only one section in an area, the Merge, Move and Delete commands do not display. You only see the Merge command if you RIGHT click on a section that has another section of the same type below it.

Crystal Reports has a true shortcut for inserting a section below an existing section. Left click on the vertical separator bar in the section you wish to add. Hold down the mouse button until the mouse pointer changes to a double-headed arrow with a single line horizontally separating the arrows. Drag the line up or down and release. This method of inserting a new section keeps all the formatting from the section above.

29

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections Exercise 2.0 – Insert an Additional Group Header Section
1. 2. 3. 4. 5. 6.

©2008 Vision Harvest, Inc.

Create an Employee Sales report using the Employees and Orders tables in the Northwind 2008 database Group by the LastName field from the Employee table. Check on the Keep Group Together option in the Group Options tab Insert the OrderID, OrderDate and OrderAmount fields from the Orders table. Format the OrderDate field to display only the date Summarize the OrderAmount field for all levels including grand total Resize the Group Header #1 section to approx. .5” tall. Move the field title headers down to the Group Header #1 section Create a Record Selection Formula filter to limit records to only orders in 2008. The formula should look similar to the following: {Orders.OrderDate} >= Date(2008,1,1)

7. 8. 9. 10.

Place a text object into the Page Header section with the title Employee Sales Orders for FY 2008 YTD. Format the title like the illustration later in this exercise Suppress the Report Header section Add the Photo field from the Employees table into the Group Header #1 section. Be sure to place the field to the right of the field headers Save the report as Employee Sales Orders for 2008.rpt and preview the report

The report should be similar to the following illustration:

30

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

The report would look better if the photo displayed beside the records. You can underlay the Group Header #1 to accomplish this. However, if you underlay the entire Page Header the Group Name field and field headers will also display over the order information. We need to place the photo in a separate section below the Group Name field and field titles and then underlay Group Header #1b. 11. 12. Return to Design view. Insert a section below the Group Header #1 by right clicking the words Group Header #1 and choosing Insert Section Below. Move the photo into Group Header #1b. Right click in Group Header #1a and choose Fit Section RIGHT click the section name for Group Header #1b, then choose Section Expert... Notice the Section Expert now displays both Report Header sections.

13.

Exercise 2.1 – Underlay a Section
1. 2. Click the Underlay Following Sections check box in the Common tab, and then click OK. Save (Employee Sales Orders for 2008) and preview the report.

The report should look like the following illustration:

31

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

Conditionally Formatting Multiple Sections
Now that you have a nice looking employee sales report, suppose you wish to add a background color to ever other record. This is a common request in many reports and is fairly easy to achieve in Crystal Reports. To achieve the desired goal, we need to add an additional Details section, add a formatted line box to the new section , turn on underlay and finally conditionally suppress the new section every other record.

Exercise 2.2 – Conditionally Format Multiple Sections
1. 2. 3. Return to Design view RIGHT click the Details section name, and then choose Insert Section Below Draw a box to fit Details b in height and make it slightly wider than the data fields in the Details a section. Your Details sections should look similar to the following:

4.

If we preview, we see the Details b appears with every record. We now need to suppress it every other record. RIGHT-click the Details b section name from Design and choose Section Expert Click on the X+2 button next to the Suppress (No-Drill-Down) option. The Format For mula Editor opens. Enter the following formula: RecordNumber Mod 2 = 0

5.

NOTE: The RecordNumber function found in the Print State function category returns a number corresponding with the position of the record being displayed. The record number does not represent the order in which the records were returned by the database, but by the order in which they are printed (displayed) in the report. The Mod operator is found in the Arithmetic operators list. The Mod operator returns the remainder of a division between a numerator and denominator. In this case, the even number records return 0 remainder and odd number records return 1. Our formula returns a True value on even number records and will suppress those records. 6. 7. 8. Save and close the formula, but do not close the Section Expert In the Sections: list, select the Details a section and in the Common tab check on the Underlay Following Sections option and click OK Save (Employee Sales Orders for 2008) and preview the report

32

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections
The report should look similar to the following example:

©2008 Vision Harvest, Inc.

Note: The alternate row color example in the previous lesson can be improved on in a few ways, such as making sure the first record in each group has a colored background. We will achieve this through the use of Running Total fields covered in the next lesson.

33

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

Challenge Exercise – Formatting with Multiple Sections
Suppose you need to create a Quarterly Sales report showing the sales for last year (2007). This will be a summary report including a graph of the sales for each quarter and the sales totals for each employee. The finished report needs to look like the following illustrations. 1. 2. 3. 4. 5. 6. Start by creating a new report based on the Northwind 2008 database. Add the Employees and Orders tables Use the Group Expert to insert a group on the OrderDate field. Choose to print the group once for each quarter. Insert another group on the LastName field Select only records in 2007 using the is between option in the Select Expert Put the OrderDate field and the OrderAmount field into the Details section at the RIGHT side of the report. Put the field headings into Group Header #2 Summarize the OrderAmount field by OrderDate group (Group #1) and by LastName group (Group #2) Move the Group #1 Name field into the Group Footer #1 and position it close to the summary field. You may need to resize it. Do the same for the Group #2 Name field (into Group Footer #2). Reformat the Group #1 Name field to look like the following: January 2004 Add the title and the print date to the Report Header section. Format both objects similar to the example at the end of the exercise. Add the Northwind Traders logo. Add a subtitle “Quarterly Sales” as shown in the example HINT: For the 2007 Sales Report text box, add a bottom border to have a separator line. Suppress the Page Header and hide the Group Header #2 section, the Group Footer #2 section and Details section Now you are ready for the extra sections. The report needs to have a graph of the sales by quarter displayed beside the summary values using the underlay feature. Since the graph appears once on the report, you need to put it in the Report Header. To accomplish this we need an additional Report Header section. Right click on the Report Header section name, and then choose Insert Section Below Insert a chart into Report Header b. Use the Chart Expert to ensure that it is a pie chart graphing the Sum of Order Amount by Order Date. On the Options tab, display the values and format them to look like currency with no decimals ($1). Turn off the Legend. Turn off all the Auto-Text entries on the Text tab and delete any text. Click OK when finished Ensure the chart is in the left side of Report Header b section and resize to be only 4” wide. Turn on the Underlay Following Sections command for Report Header b but not for Report Header a

7.

8. 9.

10.

11. 12.

34

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections
13.

©2008 Vision Harvest, Inc.

Finally you want to add a title for the quarterly sales figures. Add a text object to Report Header a that lines up with the OrderAmount summary fields. Type Total Sales. Format the box to be bold with a bottom single border Save this report and name it Quarterly Sales Report.rpt. Preview the report

14.

Preview View

Design View

35

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

Challenge Exercise – Conditionally Formatting Using DrillDownGroupLevel
The Quarterly Sales report displays summary level information. However, when you created this report, you included the detailed information. The information in the Group #2 sections and the Details section was hidden in the previous exercise. If you drill down into the report by selecting the summary information for January 2004, you will notice the report will display column headings for the first drill down. The drill down will look similar to the following example:

Obviously we do not want the column headings to appear at this level of detail. However, we do not want to delete them, because they will serve a useful purpose when you drill down to the order details for each employee. In order to prevent the column headings from appearing at the first drill down, we use a formatting option called DrillDownGroupLevel. By using this function in conjunction with conditional suppression of a section, the column headings will display at the order detail level, but not at the employee summary level.

36

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

In this exercise, you will format the report to only display the column headings at the order detail level. 1. 2. 3. Return to the Design view. Right click on the Group Header #2 section and select the Section Expert... Locate the X+2 button beside the Suppress (No Drill-Down) option The DrillDownGroupLevel function is found in the Print State functions list. The formula for preventing the Group Header #2 from displaying at level 1 is: DrillDownGroupLevel = 1 4. 5. 6. 7. Save and close the Format Formula Editor Close the Section Expert Save (Quarterly Sales Report) and preview the report From the Preview tab, double click the value for January 2007 Notice the information for January 2007 now displays the employees and their summary information. The column headings no longer appear at this level of detail. Drill down to view the detail orders for Davolio. Notice the column headings appear above the OrderDate and OrderAmount columns. Save the report (Quarterly Sales Report) and close.

8. 9.

Tip: If you are unsure what the DrillDownGroupLevel value is for the group you are working with, create a formula with the DrillDownGroupLevel value in it and place it into the header. You will then see the value as you drill down. Once you know the value, simply place it into the Section Expert as shown above to prevent the heading from displaying on drill down. Another way of knowing the level is to assume Preview = Level 0, Group 1 = Level 1, Group 2 = Level 2 and so on.

37

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

Challenge Exercise – Conditionally Formatting Multiple Sections
Suppose you also want to include a message in the report congratulating all the sales reps with sales over $20,000 in any quarter. The message only displays when the sales person drills down on the quarter to see employee sales for that quarter. You only want the message to appear under the employee names meeting the top sales goals for that quarter. The results should look like this:

Since the sales for each employee is a summary field, there is no way to compare it with summaries from other groups. So, you need to add the message and suppress it based on a combination of which quarter it is and the employee name. 1. 2. 3. Return to Design view. RIGHT click the Group Footer #2 section name at the left of the screen, and then choose Insert Section Below Add a text box to the Group Footer #2b section. Type Congratulations, and insert the {Employees.First Name} field. Then type ! You are one of the top sales producers for this quarter. Resize the text object so it looks good to you and move it to the right side of the section, directly under the summary information for Group Footer #2a Now you are ready to conditionally suppress the Group Footer #2b section. RIGHT click the Group Footer #2b section name, and choose Section Expert... Click the X+2 button after the Suppress (No Drill Down) check box.

4. 5. 6.

38

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections
7. Enter the following formula:

©2008 Vision Harvest, Inc.

Sum ({Orders.OrderAmount}, {Employees.LastName}) < 20000 8. 9. Save and close the formula. Close the Section Expert. Save and preview the report. Double click on the January 2007 sales to see if the formula worked Save (Quarterly Sales Report)

The drill-down pages of the report should look similar to the example at the beginning of this challenge exercise.

39

Crystal Reports 2008 Designer 2 Workshop Lesson 2: Power Formatting with Multiple Sections

©2008 Vision Harvest, Inc.

NOTES

40

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature

©2008 Vision Harvest, Inc.

Lesson 3 Using the Running Totals Feature

41

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature

©2008 Vision Harvest, Inc.

Lesson Objectives
After completing this lesson, you will be able to: Understand how to use Running Totals fields Learn to create accumulated totals and to reset them automatically Create totals conditionally Define a running total to only accumulate or increment under certain conditions Create totals independent of groups in the report Now you have the control to make totals for any breaking point in the report or for all the records in the report

42

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature

©2008 Vision Harvest, Inc.

Understanding Running Totals
To make working with totals easier, Crystal Reports has the Running Total field, an automatic field that calculates totals record by record, rather than just summarizing fields at the end of groups. Running total fields work similar to formula fields. You create the running total from the Field Explorer dialog box, and then insert it into the report just like any other field. Running Total fields perform functions similar to summary fields, but provide more control over how the total is calculated and when the value is reset. You create running total fields from the Field Explorer dialog box. With the Running Total Fields: highlighted, selecting the New button will open the Running Total Dialog box.

In this dialog box, you can name the Running Total field, pick a field to summarize and a type of calculation, determine when to evaluate the field, and define when to reset the field. You can even use the Formula Editor to specify conditions on which to evaluate or reset. Once you have created a Running Total field you can use it in the report or reference it in formulas. The performance of the total is not dependent upon where you put the field in the report. It performs its calculations based upon the settings you define in the Create Running Total Field dialog box. However, proper placement of the running total within the report is suggested so the calculation makes sense when the report is reviewed.

43

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature

©2008 Vision Harvest, Inc.

Creating Running Totals for a List of Numbers
Running totals perform calculations on a record-by-record basis. That is, they evaluate for each record read in the report. For example, if you have a list of values and perform a running total that sums them, the running total adds each value to the sum of all the previous values.

Values
2 4 10

Running Total
0+2=2 2+4=6 6 + 10 = 16

The most basic type of running total is one calculating a list of numbers. You tell Crystal Reports which field to calculate and what type of calculation to perform (count, standard deviation, sum, etc.). If the report is grouped, you can also instruct Crystal to restart the calculations at each new group. In the next exercise, you are going to sum a list of Last Year’s Sales amounts for customers. The report is grouped by Region. The report also shows the Top 3 regions. Remember the grand total shows the total for all selected records. We shall use the Running Total to show a grand total for the top 3 regions. In this case we do not need to reset the running total.

Exercise 3.0 – Create a Running Total for a Top N or Bottom N report
1. 2. Begin a new report, as a blank report, based on the Northwind 2008 database and the Customers and Orders tables Select only orders placed in 2008 Hint: Use the Record Selection Formula Editor to create the filter. The filter should look like: {Orders.OrderDate} >= Date (2008,1,1) Add the OrderID, the OrderDate and OrderAmount fields to the Details section. Format OrderID to not display a thousands separator and the OrderDate to display the date only Insert a group based on the CompanyName field Resize the Group Header #1 to be .5” tall and move the field headers from the Page Header section to the Group Header #1, below the Group Name field Summarize the OrderAmount by Group #1 and Grand Total. Sort the group using the Group Sort Expert to be a Top 3 report exclude others from the report. Add a title in the Report Header section and suppress the Page Header section. The title should display the text “Customer Sales Orders 2008 YTD” and be formatted a border, drop shadow and 16pt font 9. Save the report as Customer Sales Orders 2008 YTD.rpt and preview

3.

4. 5. 6. 7. 8. with

44

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature
The report should look similar the following example:

©2008 Vision Harvest, Inc.

10. 11. 12. 13. 14. 15.

Now you are ready to create the running total. Select the Running Total Field item in the Field Explorer, and then click the New button. Name the Running Total field RT_Sales Total. Select the OrderAmount field, and then click the section. button in the Summary

The field is added to the Summary section. The sum function is the default selected in the Type of summary list. You want the field to be calculated for every record in the report, so make sure the For each record radio option is selected in the Evaluate section. You do not want to reset the running total. Your running total dialog should look as follows:

45

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature

©2008 Vision Harvest, Inc.

16. 17. 18. 19.

Click OK to save the RT_Sales Total field and return to the Field Explorer. Insert the RT_Sales Total field into the Details section of the report after the OrderAmount field. Insert the running total into the Group Footer #1 and the Report Footer as well. Save (Customer Sales Orders 2008 YTD) the report and preview it.

46

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature
The report should be similar to the following illustration:

©2008 Vision Harvest, Inc.

Note: The Grand Total for the report is $467,052.40. However, by using running totals we can get a grand total for the actual records displayed on the report, which in this case is $125,932.14. The reason for this discrepancy is due to the order in which Crystal Reports processes certain items. In the first process (pass of data) Crystal Reports calculates subtotal and grand totals as well as creates groupings. In the second process (pass of data) Crystal Reports applies TopN and Running Total fields. The way Crystal Reports processes data is covered in detail in the Using Advanced Formula Feature lesson.

47

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature

©2008 Vision Harvest, Inc.

Conditional Running Totals
There may be times when you want running total values to calculate only under certain conditions. For example, in the current report, you might want to have a count of the number of customers with sales orders higher than $5,000. You might also want to calculate the total sales for those specific orders only. In cases like these, you must enter a formula that specifies the conditions under which the running calculation should be processed. Since there are only two situations involved, to perform the calculation or not, you do not have to type an if…then…else… statement in the Formula Editor. All you have to do is specify the test for the condition. If the test evaluates to true, The running total calculates the record. If not, it does not. To create a conditional running total, just specify the Use a formula option in the Evaluate section, then enter a test for the condition. TIP: You can also use a condition to define when the running total is reset. Choose Use a formula in the Reset section.

Exercise 3.1 – Create a Conditional Running Total
1. 2. 3. 4. Return to Design view and make sure the Field Explorer is open Change the Top N sort to All (Descending) using the Group Sort Expert Start a new running total and name it RT_Count 5K Select CompanyName in the Available Tables and Fields list, then click the button to add it to the Fields to summarize box. Drop-down the Type of summary list and choose Count In the Evaluate section, choose the Use a formula radio button. Click the Enter the following formula, then save and close the Formula Workshop: {Orders.OrderAmount} > 5000 7. 8. Set the running total field to reset on the Change of group, Group #1: Customers. CompanyName - A. Then click OK Create another running total named RT_Orders 5K. Select the Orders.OrderAmount field and set the Type of summary to sum. Use the same formula seen in step 6 for the evaluation and reset on change of the ComapnyName group. Click OK Expand the height of Group Footer #1 to 1”. Delete the RT_Sales Total field in Group Footer #1 and the Details section. Add a text object to the Group Footer #1 Type There were plus a space in the text box and then select from the Field Explorer box the RT_Count 5K running total field and place it into the text box. Continue to type orders over $5,000 for a total of plus a space Add the RT_Orders 5K running total into the text object and then add a period (.) Format the text object to have a single line border with a drop shadow
48

5. 6.

button

9. 10.

11. 12.

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature
13.

©2008 Vision Harvest, Inc.

Finally, conditionally suppress the Group Footer #1 section if the {RT_#Count 5K} running total field equals zero. If a customer does not have any order over $5,000, you do not want to see the group footer. Save the report (Customer Sales Orders 2008 YTD) and preview

14.

The report should look like the following illustration.

15.

To see another advantage to running totals, add a formula that calculates the RT_Sales Total as a percentage of the OrderAmount summary. Create a formula named LargeOrdersPct and add the following formula: {#RT_Orders 5K} % Sum ({Orders.OrderAmount}, {Customers.CompanyName})

16. 17.

In the Group Footer #1 text box, add the following text: Large orders represent plus a space. Add the LargeOrdersPct formula followed with a percent symbol (%) Add the remaining text: of total sales revenue. The final text box should look similar to the following example:

18.

Save (Customer Sales Orders 2008 YTD) the report and close it

49

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature Exercise 3.2 – Using Running Totals as a Line Counter
1.

©2008 Vision Harvest, Inc.

Create a new report that only shows the last ten order transactions for each employee. This report uses the Employees and Orders tables from the Northwind 2008 database Group on the Employees LastName field Insert the OrderID, OrderDate and OrderAmount fields in the Details section. Format OrderDate to show as a date without time and the OrderID field to display without a thousands separator Place a text object in the Report Header section with the title Recent Sales Orders. Format the title as shown below Move the field headers from the Page Header section to the Group Header section under the Group #1 Name field. Resize the Group Header #1 as needed Save the report and name it Recent Orders.rpt. Preview the report. The report should look like the following example:

2. 3.

4. 5. 6.

To view only the most recent ten transactions by date, you must sort the OrderDate field in descending order. Then you need to create a running total that counts the orders and conditionally suppresses the Detail section if the order count is greater than ten. 7. 8. Using the Record Sort Expert, sort the OrderDate field in descending order. Create the running total and name it RT_Line Count. Select the OrderID field. Set the summary to count, evaluate it for every record, and reset it at the change of the LastName group. Place the RT_Line Count running total field in the Details section after the OrderAmount field. Delete the field header created for the running total Preview the report and check to be sure that it restarts numbering at a new group. Save (Recent Orders) the report
50

9. 10.

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature

©2008 Vision Harvest, Inc.

In order to show the last ten transactions per customer, you are going to conditionally suppress the Details section. 11. Open the Section Expert dialog box. Make sure the Details section is selected in the Sections: list. Click the button beside the Suppress (No Drill-Down) check box.

12. 13. 14.

Create the following formula: {#RT_Line Count} > 10 Save (Recent Orders) and preview the report. When finished, close the report

The report should look like the following illustration:

51

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature

©2008 Vision Harvest, Inc.

Challenge Exercise – Creating a Conditional Running Total
Suppose you need to create a list of customers in Canada and the USA. You do not want to group the report, but you do need to see sales totals for each of the countries. You can use a conditional running total for the sales figures. 1. 2. 3. Start a new report based on the Northwind 2008 database and the Customers table Add the CompanyName and LastYearsSales fields to the Details section Select only those records with a country of Canada or USA. Use the ‘is one of’ option from the Select Expert or manually create the filter in the Record Selection Formula Editor with the following formula: {Customers.Country} in [“Canada”,”USA”] 4. 5. 6. Sort the records alphabetically on CompanyName Create a running total field called Canada Total. Select the LastYearsSales field and a sum operation. Select Never in the Reset section In the Evaluate section, choose Use a formula. Then create the following formula: {Customers.Country} = “Canada” 7. 8. Create a running total field called USA Total. Use the same settings and a formula that sets the Country = “USA” Create a text object in the Report Footer. Type Total for Canada: Create another text object below the first one and Type Total for USA: Insert the two running totals to the right of the appropriate text objects. Format the text objects to be bold. Format the running totals to be bold with a fixed currency symbol. It should look like the following: Total for Canada: Total for USA: {#Canada Total} { #USA Total}

9.

NOTE: Running totals are indicated in Crystal Reports by the # sign. 10. Save the report and name it USA Canada Sales.rpt. Preview the report, and then close it

52

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature

©2008 Vision Harvest, Inc.

The USA Canada Sales report should look like the following illustration:

53

Crystal Reports 2008 Designer 2 Workshop Lesson 3: Using the Running Totals Feature

©2008 Vision Harvest, Inc.

NOTES

54

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Lesson 4 Prompting with Parameters

55

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Lesson Objectives
After completing this lesson, you will be able to: Create parameter fields and use them to select records Learn how to define the value type, set up the prompt, and even set a default value. Maximize the usability of a report with parameters that allow record selection based on different values whenever you run the report Create Pick Lists Help users fill in parameter prompts by giving them a list from which they can choose a value Create Dynamic Pick Lists Help users fill in parameter prompts by giving them a dynamic list from which they can choose a value Insert parameter fields in text objects Use parameters to define text that is used in titles or comments Use parameter fields in conditional formats Create reports that make decisions based on user input Set up multiple parameter fields Use parameters to define date ranges or number ranges for information being reported Respond to parameter prompts See how easy it is to answer parameter prompts when viewing or printing a report Limit data entry into parameter fields Make data entry in to parameters easier by limiting the length or the range, by specifying masking characters, or by entering separator characters Use parameters to sort reports Allow users to sort reports on the fly by entering a parameter that is used later for arranging the records in the report Use parameters for group sort direction and n value in Top N reports New to version XI is the ability to use a parameter so the user of the report can decide group sort direction at run time. You can also now have a parameter for the value of N in a Top N report Cascading parameters A cascading parameter is one where the next level of parameter values depends on the original parameter selection

56

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Parameter Fields Overview
Suppose that you are creating a report that shows sales by product type. The sales team in your company needs to see this information for marketing. They need information tomorrow for California to put together a large advertising campaign. However, next month they are going to need the same information for New York to decide if marketing needs a boost there. Six months from now, they may need the same information for states in the Midwest. Parameters can give a single report the flexibility to be used in all these situations. Parameter fields are fields that prompt you to specify a value each time you refresh the data in your report. When you supply a value, the program runs the report using that value. By using parameter fields in formulas, selection formulas, and in the report itself, you can create one report that you can modify quickly, as needs change. So how would you use parameters? The following is a list of suggestions for using parameters to increase the power and flexibility of your reports: Use parameters in selection criteria as suggested above. Parameters allow you to select records based on whatever values you need Insert parameters in formulas. Suppose you have a formula that calculates sales tax, but you use the report for different counties that have different sales tax rates. Create a parameter that prompts for the rate. The formula calculates with a different rate whenever you run the report Parameters can be used to insert text into the report. For a regional sales by product type report, you might want to add a title that includes the name of the region. Use the parameter field to add that value to the text object Use parameters in place of hard coded values to perform conditional formatting. Suppose you want to display all Last Year’s Sales values under $100,000 in red, but the next time you run the report, you might want to display those values under $50,000 in red. A parameter lets you specify the value, then applies the formatting based on the value you enter Use parameters to enter date ranges for record selection or number ranges. Create a ranged value parameter and use it in the Select Expert to select a range of values Parameters can determine the sorting in a report. Let users enter a character that indicates whether they want to sort by Country, Region or City. Then create a formula that determines the sort field based on their entry These are only a few ideas for using parameters that greatly increase the usability of reports.

57

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Parameter Field Considerations
There are a number of things to keep in mind when you are working with parameter fields: You do not have to place a parameter field in the report in order to use it in a record or group selection formula. Just create the parameter field, and then enter it in a formula as you would any other field Crystal Reports supports parameter fields in the following data types: String, Number, Currency, Boolean, Date, Time, and Date/Time Parameter field prompts can be up to four lines long with approximately 60-70 characters per line. The prompt automatically word wraps if it is more than one line long You can use parameter fields in reports distributed over the web to prompt for record selection criteria You can create a pick list for the user to choose the parameter value rather than having to type it. The pick list can be dynamic i.e. fields from a database field or from a static pick list contained in the report itself You can designate Cascading Parameters, choosing a value in one parameter constrains the values in the pick list of the next parameter

Creating a Parameter Field
To create a parameter field, use the Field Explorer dialog box. Select the Parameter Fields item, and then click the New button. The Create Parameter Field dialog box appears.

58

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

In this dialog box, you define your parameter field. At a minimum you must enter a name and select a valid value type. All other choices are optional.

Parameter Field Options Option
Name

Description

Enter the name you want to use to identify the parameter field. Keep this short but make it easy to identify the information contained in the field. This can be up to 255 alphanumeric characters Type Select the data type of the parameter field (String, Date etc.) List of Values The list of values can be static (embedded in each report) or dynamic (refreshed from the database on demand). The list can also be scheduled or partially scheduled although these options are only available to Crystal Enterprise users and are administered using the Business View Manager Value Field Select a field and description here from a database field. You can then choose from the Action menu to append all database values. Crystal then populates a drop-down list from which the user can make a selection from the values you add to this section Value/Description You can choose to manually enter values and descriptions for the parameter field Actions You can populate default values from the field identified above or import a list from a text file or export the current list to a text file Show on (Viewer) Makes the parameter either hidden, editable or read only in the viewer panel Panel Prompt Text Enter the text for the user to prompt for parameter selection Prompt With By default the user is prompted with the value and description field. SelectDescription Only ing true here will only allow the user to select with the description field Optional Prompt Setting this option to true allows the user to not provide a value at runtime Default Value Provides a default value for the parameter field Allow custom Set this to true (default) or false to allow the user to modify existing values or values type new values for the parameter. With this set to false the user will only be allowed to choose from the list of default values. This option is not available when using dynamic parameters Allow multiple Default is false. If set to true a user can enter multiple values into the paramvalues eter field Allow discrete Default is true setting the parameter field to accept single values rather than values a range of values Allow range Default is false. When set to true the parameter field accepts ranges. The values user will be prompted for a start value and an end value. The report then displays all records within that range Min or Start Set a minimum length, date or numeric value for the parameter field. Choices depend on the parameter datatype Max or End Set a maximum length, date or numeric value for the parameter field. Choices depend on the parameter datatype Edit Mask For string parameters, you can limit entries using a set of masking characters. The characters restrict entry to certain values

59

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

To learn more about using parameters, you are going to edit the Monthly Sales by Supplier and Category.rpt report you created earlier in the class. Suppose that you want to modify the report so it shows data only for the supplier you choose. A parameter field lets you enter the supplier name you want and run the report with different suppliers at different times.

Exercise 4.0 – Create a Parameter Field
1. 2. 3. Open the Monthly Sales by Supplier and Category.rpt report Return to Design view and make sure the Field Explorer is open. Select the Parameter Fields item, and then click the button Type Supplier for the parameter name and select Number for the Type: option as we are going to select records based on the SupplierID, although the user will select the SupplierName from the parameter drop-down list Select Static for the List of Values option Drop-down the Value Field and select SupplierID; drop-down the Description Field list and select SupplierName Drop-down the Actions list and select Append all database values – you should see the default value and descriptions populated in the pick list grid Type Please select a supplier name: in the Prompt Text box Leave the rest of the options set with their default values and click OK. The parameter dialog should look as follows:

4. 5. 6. 7. 8.

60

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Using a Parameter to Select Records
You can use parameter fields in the Select Expert or directly in the record selection formula. Simply substitute the parameter field for the hard coded value. Once you have created the parameter field, it becomes available in any field list within Crystal Reports. A Parameter field is shown with a in front of the field name. It is also visible in some locations where other fields are not. For example, you see the parameter listed in the field values list in the Select Expert.

Exercise 4.1 – Add a Parameter to the Select Statement
1. 2. 3. 4. 5. 6. 7. Click the Select Expert button and choose Record

There is already a selection criterion for the OrderDate. Click the <New> tab to add new criteria Select the SupplierID field, then click OK Click the drop-down arrow on the operator box, then choose is equal to Click the drop-down arrow on the value box The parameter you created, {?Supplier}, appears at the top of the list of values. Select the {?Supplier} parameter Click OK in the Select Expert dialog box

WARNING: The parameter and the object you are relating the parameter to MUST be of the same value type. Otherwise, Crystal Reports will not allow you to use them together in the report. For example, in the exercise, the parameter value was set to a number. This was done because the SupplierID field that will be related to the Supplier parameter is a number. If you had set the parameter value as a string, you would not be allowed to use the Supplier parameter with the SupplierID field in the record selection process.

61

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Using a Parameter Field
Once a parameter value has been defined, simply switching between Design and Preview view may not prompt for a new value. However, you can force the prompt by refreshing the records. When you click the Refresh button, Crystal Reports asks if you want to refresh using the same parameter value or select a new value.

If you choose to prompt for a new parameter value, you see the Parameter Prompt dialog box.

At the top you see the parameter field with the list of default values for selection. You can select based on id and supplier name but the supplier id is used in the record selection.

Exercise 4.2 – Use the Supplier Parameter
1. 2. 3. 4. 5. Save the report as Monthly Sales by Supplier and Category with Parameters.rpt and then click the Refresh button Select supplier 7 - Pavlova, Ltd. and then click OK Crystal Reports displays the report only with the Pavlova, Ltd. products. Switch to Design view then back to Preview view Notice that Crystal Reports does not prompt for parameters. Click the Refresh button. Choose Prompt for new parameter values option, then OK

Select 4 - Tokyo Traders, then click OK

62

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Using the Parameter Panel
Crystal Reports 2008 introduces a new feature called the Preview Panel. The Preview Panel offers the Groups Panel, the Parameters Panel and the Find Panel.

The Parameters Panel provides a new way to manage and use parameters. In many ways it duplicates the process used in the previous exercise. However, it offers a few more benefits, such as: Prompt for Parameters for prompting for new parameter values. Using this button is faster than the traditional approach of Refreshing data, by avoiding the Refresh Report Data dialog Remove Value allows you to very quickly remove parameter values you may have chosen without automatically applying the changes Revert All Changes makes it easy to change your mind and undo all value changes made. It reverts back to the last value used to produce a preview or export report view Apply Changes will apply the new parameters and refresh the report view Parameter Prompt Bar displays the parameters prompt defined when the parameter was created. Under the prompt bar is a list of currently stored parameter values. The prompt bar also provides the ability to hide or show the current parameter values. Also, values can be added or changed under the prompt bar NOTE: The Preview Panel and, consequently, the Parameter Panel is only available from the Preview tab. For parameter prompts to appear, the Show on (Viewer) Panel parameter option must be set to either Editable or Read only. This is managed in the Edit Parameter dialog.

Exercise 4.3 - Using the Parameter Panel
1. 2. 3. 4. If necessary, go to Preview view. If the Preview panel does not appear, click the Toggle Preview Panel button From the Parameter Panel, click twice on the 4 - Tokyo Traders value under the Supplier prompt bar and change the value to 6 - Mayumi’s Click on the Apply Changes button to refresh the report

Take some time to get comfortable with the other controls. You will notice Remove Value button is not enabled. This is because the current parameter requires at least one value, but does not allow for multiple values

63

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Creating a Dynamic Value List for Parameter Values
In the previous activities you populated the list of values from the database but the list is static. It may be that the list of suppliers changes and so the value list for the parameter field needs to be dynamic. With the static list created in the previous exercise if a new supplier is added to the database the parameter value list will not be updated.

Exercise 4.4 – Create a Dynamic Value List for the Supplier Parameter
1. 2. 3. 4. 5. Return to Design view and open the Field Explorer. Select the Supplier parameter, and then click the Edit button Change the List of Values: to Dynamic Select the SupplierID under Value list; SupplierName under Description list and Supplier as the parameter field name in the Parameters list, then click OK Click the Refresh button Crystal will not prompt for new parameter values if you simply preview. Choose Prompt for new parameter values, then click OK Steps 4 and 5 could have been performed by clicking on the Prompt for Parameters button on the Parameters Panel You still see the same list of suppliers but now if the supplier table is updated you will see the new suppliers listed. Select a Supplier of your choice Save the report as Monthly Sales by Supplier and Category with Parameters.rpt

6. 7.

Importing a Pick List
There are times when you have a list large enough to be too time consuming to manually enter. In many situations it is easy enough to find the database field containing the list values and pull those values into a static list (see steps 5 and 6 of Exercise 4.0). However, there are situations where using this method brings in many items not wanted. This forces you to spend considerable time editing the list. Another alternative is to create a report designed for exporting data into an importable parameter pick list (text file). This method takes some initial setup, but over time is a time saver in situations where your static list is constantly changing. Our situation in the following exercise is that we have a pre-built report showing Condiment sales for 2007. It is completed, tested and in production. A new user request asks for the ability to limit which condiment products are shown at runtime. In our database there are 12 products identified as condiments out of a total 77 products. If we were to pull in the products data, we would get 65 unwanted products in the list and would have to spend unwanted time deleting these values. To simplify our work and to have a resource to use in the future when the condiments product list may change, we are going to create a report for generating the pick list.

64

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters Exercise 4.5 - Create and Import a Pick List
1.

©2008 Vision Harvest, Inc.

Before we open the Condiments Sales report, we should create the new report which will generate the Pick List text file. Start a new blank report right using the Northwind 2008 database. Add the Categories and Products tables Either using the Record Select Expert or the Record Selection Formula Editor create the following filter to limit our records to Condiments only: {Categories.CategoryName} = “Condiments”

2.

3. To make sure our pick list is sorted alphabetically, we need to sort on the ProductName field. Open the Record Sort Expert and add the ProductName field to the Sort Fields: list 4. Add the ProductName field to the Details section. Be sure to make the field about 5” long to avoid any truncation during the export

WARNING: When placing the ProductName field in the Details section, position it at the very most left edge of the Details section. This prevents additional spaces to the left of each ProductName name during the export to a text file process.. When the pick list is imported into a parameter values list the spaces will also be imported making the parameter useless. Leading spaces are the common reason for this exercise not working. 5. 6. 7. 8. 9. Suppress all sections except the Details sections Any unsuppressed sections will be exported as blank lines. Click the Export button on the top toolbar. Drop-down the Format: box, then choose Text and click OK The Export to Text window will display. Set the Number of lines per page: to zero (0) to prevent pagination in the list. Leave the default 12 for characters per inch. Name the text file Condiments.txt and save it in the folder you are using for class. Save this report as Condiments List.rpt and close it Open Condiment Sales 2007.rpt, which is found in the CR2008 D2 Class Resources\L04 directory, and create a static parameter field called Condiment Products. Under Actions select Import... and import the Condiments.txt file Click OK when finished with step 9 Save the report as Condiment Sales 2007 with Parameters.rpt In the Record Selection Expert delete the record selection on CategoryName and create a new record selection for {Products.ProductName} = {?Condiment Products}

10. 11. 12.

65

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters
13.

©2008 Vision Harvest, Inc.

Refresh the data and notice that you can not choose more than one Product Name in the following dialog:

Adding Parameter Values to Text Objects
If you use parameter fields to select records, you might want text somewhere in the report that reflects that selection. For example, in the Condiment Sales 2007 with Parameters report, you might want the title to indicate the product name chosen by the user at runtime. You can insert the parameter into the text object from the Field Explorer, just like any other field. When the report updates with a new parameter, so does the text.

Exercise 4.6 – Add a Parameter Field to a Text Object
1. With the Condiment Sales 2007 with Parameters report still open, add a text object to the Report Header to read For Product: plus a space. After the space, add the parameter field Condiment Products Make sure the new text object is formatted to match the original title similar to the example below:

2.

3.

Save (Condiment Sales 2007 with Parameters) and preview the report Crystal Reports adds the current parameter value to the title.

66

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Allowing Multiple Values in Parameters
You can permit users to enter more than a single value for any parameter. In the current report, this would let the user select more than one product and run the report for all products selected. To allow multiple values, set Allow multiple values to true in the Parameter Field dialog box.

Exercise 4.7 – Allow Multiple Entries in the Region Parameter
1. 2. 3. 4. Return to Design view and edit the Condiment Products parameter Change Allow multiple values from False to True You may want to change the text prompt to read “Select products and move selected products to the Selected Value list” . Click OK Refresh the data, and then prompt for new parameter values Notice the different dialog in the Parameter prompt dialog box. Select Aniseed Syrup and move to Selected Values: using the Genen Shouyu and move it over as well. Click OK button. Select

5. 6.

Save (Condiment Sales 2007 with Parameters) the report, but do not close it.

NOTE: Crystal runs the report with both regions. But notice the text in the title. Only the first product, Aniseed Syrup, appears in the title. The reason for this is the parameter is actually an array value holding several item values selected by the user. Crystal Reports will only show the first value, or index, in the array. In order to display all index values in the parameter array, a formula must be written, which will be covered in the Advanced Formula Features lesson.

67

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Using Multiple Parameter Fields in Reports
Often, complex reports require more than one prompt from a user. Suppose, for example, the Monthly Sales report you created earlier needs to be used in different time frames. Right now, it is set up to view only orders in 2007. But, suppose you sometimes needed to limit the view to only orders from a particular quarter. A date range used along with the supplier parameter for selection would give you the ultimate flexibility in defining, not only the supplier name, but also the time frame for which you wanted information. For this type of situation, you can create as many parameters as you need.

Specifying and Limiting a Range for a Parameter
Crystal Reports gives you the ability to specify ranges with parameters. If you change the value of Allow range values from false to true, you are then prompted for start and end values in the parameter prompt. You enter the start value and end value, and then Crystal Reports selects all records that fall between the two values. For example, if you enter values 5 and 10, the report displays all records with values between 5 and 10. When you select Allow Range Values you can then enter a start and end date for the range as shown below.

You can use ranges on any type of field values, including numbers, dates, and even text. For example if you add a start value of A and an end value of L, the report displays all records that fall within the alphabetical range of A-L. TIP: If Allow multiple values is toggled on, and the Allow discrete values option is selected, you can enter multiple values. If Allow range values is selected with Allow multiple values, you can select multiple ranges.

68

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

When you use a range value type of parameter for selection, you can simply select the is equal to operator in the Select Expert, then set the field to be equal to the parameter. There is no need to use is between since the parameter field prompts for the starting and ending values. This is a simplification process by Crystal Reports. In actuality, Crystal is able to determine the proper query structure based on the parameters option settings. With Date and Date/Time parameter types, Crystal thoughtfully provides a calendar from which you can select dates easily. The calendar appears, not only when you select default start dates, but also when the user is prompted to fill in the parameter value.

Use the arrow buttons on the left side of the month/year to move forward and backward one month at a time. The arrow buttons on the right side move forward or backward one year at a time. Then just click the date you want.

Exercise 4.8 – Use Multiple Parameter Fields to Specify a Date Range
1. 2. 3. 4. 5. Open Monthly Sales by Supplier and Category with Parameters.rpt. Go to Design view Create a parameter called Order Dates Select a Date for the Type: option In the Value Options: list, type a prompt of your choice, such as ‘Choose or enter a starting date and an ending date’ Change Allow range values to True. Enter a Start value of 1/1/2006. Enter an End value of 12/31/2008. Click OK By defining the Type as a Date, we will not need to add a time to prompt values. The field (OrderDate) we will use for this parameter is defined as a DateTime datatype in the database. Using the Date type for the parameter makes it easier for us to use in the report since times are not actually stored in the database. One downside to this approach is the Select Expert will not make the parameter available to us since the data types do not match. This means we will manually have to create the selection formula. Ultimately, this is the best approach since your end users will not be required to enter times in the parameter prompt, providing a simpler user experience.

69

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters
6. 7.

©2008 Vision Harvest, Inc.

Now change the select statement to use your parameter. Click the Report/Selection Formulas/Record to open the Record Selection Formula Editor The OrderDate has a record selection using the between operator, which looks like this in the Record Selection Formula Editor: {Orders.OrderDate} in DateTime (2007,1,1,0,0,0) To DateTime (2007,12,31,0,0,0) You can find the {?Order Dates} parameter in the Report Fields list. Change the OrderDate filter to the following: {Orders.OrderDate} = {?Order Dates} and {Suppliers.SupplierID} = {?Supplier}

8. 9.

Now refresh the data. Choose the 4 - Tokyo Traders supplier in the top parameter box In the Order Dates box select 1/1/2007 as the start date using the popup calendar and 3/31/2007 as the end date. Your parameter dialog should look as follows:

10.

Refresh the report and try to enter a date outside the range you provided when setting up the parameter report such as 1/1/2005. You will see the following dialog:

Notice that Crystal resets both the Start and End of Range to their the previous values. 11. Save (Monthly Sales by Supplier and Category with Parameters.rpt) the report

70

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Using Parameters in Conditional Formatting
The power of parameters is practically unlimited. In addition to selection and text objects, you can also use parameters in any formula, including formulas used to conditionally format fields and sections. Once you have created a parameter field, it becomes available in the Fields list in the Formula Editor. You can add it to formulas to replace other fields or hard coded values. Suppose you have been tasked to create a report of employee sales for 2008 as you created in Lesson 2. The requestor needs to see all the employees, but wants to apply a message to the sales reps with sales of $60,000 or more. However another Sales Manager wants to run the report and apply a message to those whose sales are $50,000 or more. There is no need to create two separate reports, instead you can create one report where the user decides the threshold value. Once you have created the parameter, you can use it in the conditional suppress formula easily.

Exercise 4.9 – Use a Parameter to Conditionally Display a Message
1. 2. 3. 4. Open the Employee Sales Orders for 2008.rpt report you created earlier in the class Go to Design view and open the Field Explorer. Click the Parameter Fields item and click the New button Type Threshold Value in the Name: box and select Number as a Type: The value type needs to be Number as all summaries are number type fields. Type: “Type the $ value for an employee’s order amount total. Employees with more sales than this value will have a congratulations message displayed.” in the Prompt Text box. Click OK Now you need to create a message. Insert a section below Group Footer 1 i.e. Group Footer #1b, add a text box with the message “Congratulations, your sales this year exceeded” , and add the parameter field to the text box Now you need to format the section to display only when the threshold is met. Open the Section Expert, make sure Group Footer #1b is highlighted and then click the conditional format button next to Suppress (No Drill-Down) Enter a formula to suppress the section when the employee’s order amount total is less than the threshold value. Find the parameter in the Fields list. The formula should look like this: Sum ({Orders.OrderAmount}, {Employees.LastName}) < {?Threshold Value} 8. 9. 10. Check the formula, save and close it Save the report as Employee Sales Orders for 2008 with Parameters.rpt and preview the report Type 50000 when prompted for the Threshold Value value Crystal Reports displays the message for only those employees with an Order Amount greater than or equal to $50,000.

5.

6.

7.

71

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Using an Edit Mask to Limit String Parameters
For string parameters, you can enter an Edit Mask that will validate the entry of a parameter value. Unfortunately, the Edit Mask feature no longer assists the user in typing the values and only acts as a validation tool. Nevertheless, the Edit Mask is a great tool for forcing end-users to type values correctly and limit the report’s ability to process until a valid value is entered. Edit Masks use specific characters as masking characters. The following table contains a list of masking characters and how they are used:

Character
A a 0 9 # L ? & C .,:;-/ < > \ Password

Masking Characters Used in an Edit Mask for a Parameter Description
Allows an alphanumeric character and requires the entry of a character Allows an alphanumeric character and does not require the entry of a character Allows a numeric digit and requires the entry of a character Allows a numeric digit and does not require the entry of a character Allows a digit, space, or +/- and does not require the entry of a character Allows a letter and requires entry of a character Allows a letter and does not require entry of a character Allows any character or space and requires the entry of a character Allows any character or space and does not require the entry of a character Separator characters. Inserting separator characters is like hard coding the formatting for the parameter. When the field is placed on the report, the separator character appears in the field as a character Causes following characters to be converted to lower case Causes following characters to be converted to upper case Causes the following single character to be taken as a literal. NOTE: use this to add separators that are different from the defined separator characters If you set the Edit Mask to “Password”, you can create a conditional formula to specify that certain sections of the report are visible only when certain user passwords are entered To see how an edit mask works you are going to create a simple customer phone list. You want the user who runs the report to be able to look up a single phone number by typing it in. If the user does not type a phone number, the report should run with all customers and their numbers. The USA phone numbers in this database take the format of (###) ###-####. You will set up a phone parameter using an edit mask that guides the user to enter all 10 digits, including the dashes. You are going to specify a default value of (555) 555-5555. You will then use a selection formula to show all phone numbers if the user chooses the default.

72

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters Exercise 4.10 – Use an Edit Mask for a Parameter
1. 2. 3. 4. 5. 6.

©2008 Vision Harvest, Inc.

Start a new report on the Northwind 2008 database and the Customers table Add the CompanyName and the Phone field to the Details section Filter the records to only those customers in the USA Create a new parameter called Phone. In the prompting text, tell the users that if they leave the phone set to the default, they will see all customers. Click in the default value box and type (555) 555-5555 Click in the Edit mask text box and type the following masking characters: (000) 000-0000 The zeros are required characters, digits only. The ( , ) and - are defined separators, so you do not need the \ (literal) before it. Your Value Options: should look as shown below:

7. 8.

Now you need to create a formula for the selection criteria. From the Menu bar, select Report|Selection Formulas/Record… to open the Record Selection Formula Editor Edit the text in the Record Selection Formula Editor to look like the following formula: {Customers.Country} = “USA” and (If {?Phone} = “(555) 555-5555” Then True Else {Customers.Phone} = {?Phone}) The If statement instructs Crystal to display all numbers if the parameter equal to “(555) 555-5555, which means the parameter is set to the default value. If the user types a different phone number in the parameter, Crystal selects only the record with that phone number.

9. 10.

Save and close the Record Selection Formula Editor Save the report and name it USA Customer Phone List.rpt. Then refresh the data and try the parameter. The first time you try it, accept the default. You should see all customers. Refresh the data again. This time type (505) 555-5939 into the parameter prompt. Notice that you need to type the separators. Click OK. You should see only one record for Rattlesnake Canyon Grocery
73

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Sorting with a Parameter
Parameter abilities are endless in Crystal Reports. One of the things you might not have thought of is to use a parameter to allow the user to define how records are sorted or grouped. To use a parameter for sorting, you will create a number parameter. You can then create a formula that defines the field for the sort based on the value in the parameter. For example, suppose you want to allow the user to define whether to sort by Country, Region or City. You could set up a parameter that tells the user to select City or Region or to accept the default for Country. Once you have the parameter created, it is a simple mater of defining what field to output in a formula based on the parameter’s value and then sorting on the formula field.

Exercise 4.11 – Use a Parameter to Define the Sort Order for a Report
1. 2. 3. 4. Create a new report using the Northwind 2008 database and use the Customers table Add the Country, Region and City fields to the Details section Create a new parameter called Sort Parameter. Enter an appropriate prompt. Set the Type: to Number Under the Value and Description lists enter three values for the report user to select: Value: 1 Description: Country Value: 2 Description: Region Value: 3 Description: City 5. 6. 7. Set the Default Value to 2 (Region) You can drop down the box and select one of the values you entered above. You do not want the user to type any other value than the three you provided in the list. Change Allow custom values from its default of True to False and then choose OK Now create a new formula called Sort Formula. Enter the following formula: If {?Sort Parameter} = 1 Then {Customers.Country} Else If {?Sort Parameter} = 2 Then {Customers.Region} Else {Customers.City} 8. 9. 10. 11. Check your formula, and then save and close out of the Formula Editor Click the Record Sort Expert button

Add the Sort Formula formula to the Sort Fields: Test the report to see how it works. Refresh the data and select City. Try it again with Country. Then try it with the default value Notice that you cannot type values in the box, the background is gray and will not accept typed characters. Save the report as Parameter Sort.rpt

12.

74

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Group Sorting with a Parameter
A relatively new feature is the ability to use a parameter to determine group sort order at run time. When you create a group there is an option to use a formula as a group sort order as shown below:

Exercise 4.12 – Use a Parameter to Define the Group Sort Order for a Report
1. 2. If necessary, open the Employee Sales Orders for 2008 with Parameters.rpt report Create a parameter field called Group Sort Order, make it a Number type, make sure the user cannot enter their own values and provide it with three values: Value: 1 Description: Ascending Value: 2 Description: Descending Value: 3 Description: Original Order 3. Open the Group Expert, click on the Employees.LastName group in the Group By: list and then click the Options... button. Check on the Use a formula as Group Sort Order option and then the X+2 button. Your formula should look as follows: If {?Group Sort Order} = 1 then crAscendingOrder Else If {?Group Sort Order} = 2 then crDescendingOrder Else crOriginalOrder 4. 5. Refresh your report and try out the different values to see how the groups are sorted Save (Employee Sales Orders for 2008 with Parameters.rpt) the report

WARNING: There appears to be unusual behavior when choosing Original Order. It seems Crystal Reports creates a grouping each time an employee last name is encountered. In all previous versions the behavior was to create the same number of groups as the other choices, but keep them in the order they first appeared.

75

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Using a Parameter to set N in a Top N or Bottom N report
Another recently new feature is the ability to set the value of N in a Top N or Bottom N report. You simply create a parameter field to prompt for N and use it in the formula editor from the conditional format button shown below.

Exercise 4.13 – Use a Parameter to set N in a Top N report
1. 2. Using the Employee Sales Orders for 2008 with Parameters.rpt, return to Design view if necessary Create a parameter field called Value of N that is numeric; has a Min Value of 1 and a Max Value of 10 with a Default Value of 3. Click OK when finished Click the Group Sort Expert button, set For this group sort to TopN and click on the conditional formatting button next to the N value. Simply enter {?Value of N} as the formula. Save and close all open window dialogs Refresh the report and enter the following values for the prompts: Threshold Value: Group Sort Order: Value of N: 5. 6. 0 (this means all sales total over zero will be included) 1 - Ascending 3

3.

4.

Click OK when finished and preview the results Save (Employee Sales Orders for 2008 with Parameters) the report and close it when finished

Your Groups Panel should look similar to the following:

76

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Displaying Parameter Fields
When a parameter field has a single value then you can simply display it on the screen or in a text object. However, often the parameter field is an array of values such as a selection of employees or a range of values as in a date range. Suppose you had a report that contained a date range, like in the Monthly Sales by Supplier and Category with Parameters report. If you wanted to display the date range selected you would need to create a formula to extract the begin date and the end date from the Date parameter. You will learn about extracting these array values in the next lesson when you begin working with advanced formulas.

Cascading Parameter Fields
If you are creating a dynamic parameter field you can choose to make it a cascading parameter field which narrows the selection of each parameter field dependant on the first parameter field selection. For example imagine that you are looking for customers in a particular city. You can create a cascading parameter field so that first you pick the country you are interested in; you can then select the region field (the only regions you will see are those in the country you have selected); having selected the region you then select the city. In this case the cities presented in the values list are only the cities in the region you selected. An example in the Northwind 2008 database you have been using is as follows: In an earlier example we created a products pick list for condiment products only. What if we would like to dynamically pick products from other product categories? A simple solution is to create dynamic cascading parameters which first allows us to pick a category such as Condiments or Confections which then populates our second parameter for products related to that category.

Exercise 4.14 – Creating a Cascading Parameter field.
1. 2. 3. Open the report Condiment Sales 2007.rpt report found in the CR2008 D2 Class Resources\L04 directory Save the report as Category Sales 2007 Create a new parameter and name it Product Name, make it Dynamic and enter prompting group text such as: Select Category and then Product Name for your report Click on the Click here to add item in the Value list and select the CategoryID from the drop list. For the Description select the CategoryName field. On the next line choose the ProductID field for Value and ProductName field fro Description. Do not select to Click to create a parameter with the CategoryID line, but do select it for the ProductID line. Click OK. This will bind the parameter field to a ProductID and indicate that the other parameter is simply a vehicle to get to the ProductID. Your parameter dialog should look as follows:

4.

5.

77

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters
6.

©2008 Vision Harvest, Inc.

Open the Record Selection Formula Editor and modify the formula to match the example below: {Orders.OrderDate} in Date (2007,1,1) to Date (2007,12,31) and {Products.ProductID} = {?Product Name - ProductID} Since the parameter will display on those products in the selected category we can filter against the ProductID field rather than the CategoryID

7.

Refresh the data. Choose the Confections category in the first drop list. Notice the second drop list populate only with products in the Confections category. Select the 48 - Chocolade in the second drop list and then click OK The report should only display sales for the product Chocolade. However, one problem we see is the title is not correct since it list this as Condiment sales. An easy fix is to replace the word Condiment with the CategoryName field. Resize as needed

8.

We can do this quick fix because we know all records have the same data value for the CategoryName field. Crystal simply pulls the value from the first record since the title is in the Report Header. If the text box was in the Report Footer, then Crystal would pull from the last record. Making use of this technique saves time by not having to write formulas. 9. We would like the ability to add multiple products as part of our filter. Edit the Product Name - ProductID parameter, select the ProductID value row and change the Allow multiple values option to True. Click OK Each value row has its own set of manageable options 10. Refresh the report for new parameters and select the 7 - Produce Category. From the Products list, add 14 - Tofu and 74 - Longlife Tofu items to the Selected Values: list. Click OK when finished Save (Category Sales 2007)the report

11.

The beginning of the report should look similar to the following example:

78

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Challenge Exercise – Using Parameters
The Recent Orders.rpt report that you created in an earlier exercise needs to be more flexible. Sometimes users want the last three orders, other times they might want to see the last five or only the last one. To gain this flexibility, you want to give the user the option of showing 1 to 10 transactions. In addition, you want to be able to specify a date range for displayed orders. 1. Open the Recent Orders.rpt report. Create a parameter called Last Transactions. This is going to hold a number value. In the prompt, tell the user to enter the number of last transactions they wish to see. Specify this must be a number between 1 and 10 Set the Min/Max Values to a minimum of 1 and a maximum of 10. Set the default value to 3 You want the parameter to do the same thing the number 10 is doing in the conditional formatting formula that suppresses the Details section. Modify the formula to the following: {#RT_Line Count} > {?Last Transactions} 4. Refresh the data and respond to the parameter prompt. Now that you know the RT_Line Count running total works, you can delete it from the Details section. You also need to create a date range parameter and change the Record Selection on the OrderDate field. Return to Design view. Select the RT_Line Count running total, its title and delete them Create a date parameter named Date Range to use in the record selection formula. Set the value type to Date. Set Allow range values to True and then click OK Add a Record Selection criteria that sets {Orders.OrderDate} equal to the Date Range parameter: {Orders.OrderDate} = {?Date Range} 8. Create a text object that displays the transaction value HINT: Insert the Last Transactions parameter into a text object in the Report Header that says something like this: Last {?Last Transactions} Transactions 9. 10. Refresh the report and enter 3 as the number of Last Transactions with a begin date of 2/1/2007 and an end date of 4/30/2007 Save this report as Recent Orders with Parameters.rpt

2. 3.

5. 6. 7.

79

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters
The report should look like the illustration below:

©2008 Vision Harvest, Inc.

WARNING: This Challenge Exercise must be completed. This report will be used in class exercises in the next lesson.

80

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

Challenge Exercise – Displaying Parameters
1. 2. 3. 4. 5. In the Recent Orders with Parameters report. Create a parameter called Employee Name. This will hold a string value. Add a Value of ALL with a Description of All Employees. From the Value Field drop-list, select the LastName field from the Employees table. From the Actions drop-list select the Append all database values Change Allow multiple values to True In order to select a specific employee, a list of employees or all employees, you need to modify the Record Selection Formula. Your final formula should look like the following: {Orders.OrderDate} = {?Date Range} and (If {?Employee Name} = “ALL” Then True Else {Employees.LastName} = {?Employee Name}) This formula allows the user to select all employees if the value of the parameter is set to ALL. Otherwise, the employees returned to the report are based on the values entered into the parameter. 6. 7. Save (Recent Orders with Parameters) the report Refresh the report and run the report selecting employees Davolio and Dodsworth; last 3 transactions and a date range of 1/1/2007 to 3/31/2007. Your report should look like the one below:

WARNING: This Challenge Exercise must be completed. This report will be used in class exercises in the next lesson.

81

Crystal Reports 2008 Designer 2 Workshop Lesson 4: Prompting with Parameters

©2008 Vision Harvest, Inc.

NOTES

82

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

Lesson 5 Using Advanced Formula Features

83

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

Lesson Objectives
After completing this lesson, you will be able to: Understand how Crystal Reports reads the records when it creates the report An understanding of the background process Crystal Reports uses when it creates a report makes you an intelligent report writer Know which Evaluation Period to apply to run a formula Now, you have the control to make Crystal Reports work for you to create complex formulas and perform powerful evaluations Declare variables, assign values to them and use them Increase your reporting power by performing calculations then holding them in memory for later use. Crystal Reports can then calculate running totals, perform calculations on changing data, or run very complex formulas Use multiple statements in a formula Expand the complexity of formulas by using several statements in one formula Manipulate parameter arrays containing multiple values Learn what an array is and how to store values in arrays. Also, discover how to pull values from arrays. Multiple value parameters are actually arrays Review conditional statements Practice using multiple nested if…then…else statements and review how they work Use the Formula Debugger Sometimes you come across run time errors in formulas such as division by zero. The debugger helps you determine where the error is occurring

84

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

Understanding How Crystal Reports Processes the Data
Sometimes the complexity of the report you need to create requires that you understand how Crystal Reports processes data for the report and when it performs certain tasks. If you become familiar with the two-pass method of Crystal Reports, you have the ability to do complex reporting and formula manipulation. You will have the capability to do many previously impossible complex formulas.

What Is a Pass?
A pass is a process by which Crystal Reports reads the data from the database. During each pass, Crystal Reports reads and manipulates the records. Depending on the features used in the report, Crystal Reports may make from 1 to 3 passes over the data. This allows for complex reporting and formula manipulation.

Pre-Pass#1
Before Crystal Reports ever contacts the database, it evaluates flat formulas. A flat formula is a formula that does not contain any fields from the database; for example, 100 * 25 would be a flat formula. Special fields that put in the print date, formulas that calculate dates from the current date or times from the current date or times, and formulas that contain just numbers, are good examples of flat formulas. During this time, Crystal Reports also identifies parameters and reads text objects in the report. This evaluation time is known as the BeforeReadingRecords process.

Pass #1
During the first pass, Crystal Reports begins reading the database records. This evaluation period goes through several processes: Retrieves records – This is a rather simplified statement. In reality, many things occur to send a query to the database and then get data back. Crystal evaluates the fields and tables you need and selection criteria, then generates an SQL query, sends it to the database and retrieves the data Evaluates recurring formulas – These are formulas that contain database fields, but do not contain any references to summaries. This process is iterative, that is, it repeats over and over for each record pulled from the database Applies the record selection formula – If the record selection statement contains summaries or non-SQL convertible comparisons, then Crystal does not pass that portion of the statement directly to the database. These statements are evaluated and applied to the returned records at this point WARNING: Crystal Reports may not always provide the entire selection criteria to the database. For example, {Orders.Ship Date} > ({Orders.Order Date} + 5) is a test to find only records where the ship date is greater than five days after the product was ordered. If you looked at the query sent to the database, you would see that this test would be missing. It is missing because Crystal Reports cannot bundle the test as part of the SQL query and therefore, must wait for the data to return, and then apply the test. However, you can use SQL expressions to overcome performance issues like this one. Also, Crystal Reports (since version 9) allows the ability to develop your own SQL statement as the data source.
85

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

Performs grouping, sorting and totaling - Now that the data is retrieved, formulas processed and records evaluated, Crystal Reports organizes the records according to specified groups and sorts them. It also summarizes or totals all the appropriate records. This is an extremely important step for consideration in formulas. If you are going to create a formula that is based on specified groups, sorting or summaries, you must force the formula to run after this process is complete. Remember that most formulas have already been run at this point Generates cross-tabs, maps and charts – Crystal generates any cross-tabs , maps and charts that are based on database fields here. This is not the same as rendering the images. These items are really just different types of grouping , so at this stage the grouping information is collected. Rendering occurs in Pass #2 Stores and saves records – Crystal stores all the saved records, grouping and summary totals in memory and to temporary files. Crystal does not read the database again, but instead uses this saved data for all further processing Applies saved data selection formulas - A new feature in Crystal Reports 2008 is the ability to create parameterized record filters to a report that has already processed. This provides a mechanism to query larger record sets from the database for the enduser to work with without needing a new database query generated each time the end-user wants a different report view. This evaluation time is known as WhileReadingRecords.

Pre-Pass #2
The Group Sort Expert process runs as an intermediate process before the second pass on the data. Hierarchical grouping also occurs here. These features do not actually require the records to be read. Instead, they look at the grouping and order the groups as specified.

Pass #2
The second pass is devoted to the report’s formatting selections for previewing and printing. This evaluation time is known as While Printing Records. This period goes through the following processes: Reads saved records – Crystal Reports reads the saved records one at a time together with their subtotals. The records are now evaluated for display purposes Applies group selection formula –The group selection formula is evaluated at this point because it relies on the grouping and summarizing which is performed in the first pass Executes running totals - The running total fields sometimes rely on the report being grouped and sorted first, so they are run during the second pass

86

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

Processes print time formulas – Formulas that include the WhilePrintingRecords function or subtotals or summaries are evaluated at this time. These formulas have been specifically defined by the report creator for evaluation after the first pass. Some examples of print time formulas are formulas that calculate: - Percent of subtotals - Manual running totals or running averages - Formulas using RecordNumber, GroupNumber, Previous, or Next functions Generates cross-tabs, charts and maps – Cross-tabs, graphs and maps images are rendered here Runs subreports – Subreports have to be evaluated during the second pass because they are not really read until Crystal formats the page on which they occur. On demand subreports are run when the user clicks on them Generates pages on demand – Crystal generates reports with Page on Demand technology. This means, as you request to view a particular page, it reads the records, formats them and generates the page This evaluation time is known as WhilePrintingRecords

Pass #3
If the report uses the special fields, Total Page Count or Page N of M, a third pass is necessary to calculate the page count. Using these special fields effectively turn off the Page on Demand feature since all pages have to be processed before the first page can be displayed.

Using Evaluation Time Functions
Crystal Reports has four functions you can use to specify when a particular formula is run. Three of the functions have the names of the evaluation periods. You can find these functions in the Functions list (middle list in the Format Editor) in the Evaluation Time category. BeforeReadingRecords – specifies that a formula will be processed before the first pass. Crystal Reports returns an error message if you attempt to include elements in the formula that must be evaluated at a later time, such as database fields, groups, etc WhileReadingRecords – forces the formula to be processed while the program is reading database records. Crystal Reports again returns an error message if you attempt to include elements in the formula that must be evaluated later, such as groups WhilePrintingRecords – defines that the formula will be evaluated after the first pass. For formulas that depend upon the first pass processes being performed before the formula is evaluated, this function is valuable. By including this function at the beginning of the formula, you ensure that the formula is processed after the first pass, when grouping, summarizing and sorting have already been done EvaluateAfter(x) - If two formulas are going to be run during the same evaluation time, and the order in which they are run makes a difference in the report, you can use this function to control the order in which they are run
87

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features Working with Variables

©2008 Vision Harvest, Inc.

Variables are useful temporary fields that can carry their values from record to record. Unlike a constant value, which is fixed, variables can hold values that change from time to time. Variables also allow you to store information for use later, or in another formula. There are three steps required for using a variable: 1. 2. 3. Declare it Set the value Use it in a formula

Declaring a Variable
The first step to using a variable is to declare or name it. When you declare a variable, you give it a name and tell Crystal Reports what type of variable it is. The variable name must follow these rules: The name can contain up to 254 characters The name must start with a letter and can contain letters and numbers No spaces are allowed in the name The name cannot be the same as a CR operator or built-in function NOTE: If you declare a variable with the same name and data type in more than a single formula, then the formulas share the variable. This ability lets you carry the value in a variable from one formula to another. The variable needs to be defined with the correct scope. TIP: Keep variable names short, unique and easy to remember. Do not use similar names for different variables if it will cause confusion. The type of variable defines the type of data the variable can contain. There are 26 variable types, but the most commonly used ones are: NumberVar - contains numeric values which can be calculated CurrencyVar - contains currency values which can be calculated StringVar - contains any character, alpha, numeric or special characters as text BooleanVar - contains the values True or False DateVar - contains dates which can be calculated DateTimeVar - contains both date and time and can be calculated

88

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

The syntax for declaring a variable includes the variable type, then a space, and then the variable name. For example, you might want to create a date variable that contains the date that is 14 days after the OrderDate and call it DateDue. To declare the variable, you would type: DateVar DateDue

Assigning a Value to a Variable
Once a variable is declared, it needs to be assigned a value. If no value is assigned, the variable assumes a default value of zero or blank depending on the variable type. To assign a value, you use the assignment operator “:=”. For example, to assign the DateDue variable a value equal to the date 14 days after the Order Date, you would type: DateDue := {Orders.OrderDate} + 14 This statement sets the variable to the current record’s Order Date value plus 14 days and can be used for further calculations. TIP: You can declare a variable and assign it a value in one statement by using the variable type operator then the variable name followed by the assignment operator and the value you want assigned to the variable. For example to declare the DateDue variable and assign its value in one statement, you would type: DateVar DateDue := {Orders.Order Date} + 14 NOTE: Variable declarations such as StringVar x := y are listed in the Formula Editor at the bottom of the Operators list.

Using a Variable in a Formula
Once declared, a variable’s name and current value is stored in memory and can be used in the current formula or by other formulas for calculations. You can use a variable within a formula. If the formula declares several variables, the last variable that was referenced in the formula displays when you put the formula field in the report. This is important to remember as formulas get more complex. Suppose you created a formula called Display_Dates: DateTimeVar DateDue DateTimeVar OverDueDate DateDue := {Orders.Order Date} + 14 OverDueDate := {Orders.Order Date} + 60 When you place this formula field in the report, ONLY the value in the OverDueDate variable displays.

89

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

To display any variable’s value, you create a formula that contains the variable type and the variable name, and then insert that formula as a field in the report. For example, to display the DateDue in the report, create a formula named Display DateDue with the following in the formula. DateTimeVar DateDue Then place this formula field in the report. If this formula does not show any values then it needs to be evaluated at a later pass, the display formula needs to be evaluated after the formula that sets the values. In this case the first line needs to read: EvaluateAfter ({@Display_Dates});

Variable Scope
Variable scope defines how the variables in one formula are made available to other formulas throughout the report. There are three levels of scope in Crystal Reports: local, global and shared. Every variable has a scope, and this scope is specified when the variable is declared. Global - The variable is available to formulas throughout the entire current report Shared - The variable can be shared with a subreport as well as the entire current report Local - The variable is specific and can only be used in the formula in which it is defined You define the scope of a variable by including the scope type before the variable declaration. For example, a local variable would be declared like this: Local DateVar DueDate := {Orders.Order Date} + 14 Global variables are the default type. If you do not declare a scope for a variable, it automatically becomes a Global variable. One final note about variables; once it is declared and assigned a value, a variable’s contents remain in memory and available to other formulas in the report, as long as you do not define it as a Local variable. However, to use the variable in another formula, it must be re-declared it in that formula. To re-declare it, simply type the variable type, a space, and then the name of the variable. For example, to reuse the DateDue variable, you would type DateTimeVar DateDue. WARNING: In order for a variable to work in a report, it MUST be physically placed in the Design view of the report. Crystal requires this so that it can evaluate the variable calculations and store them in temporary memory for future display. If you do not need to display the calculations in Preview, simply suppress the variable in the Design view.

90

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features Separating Statements in Complex Formulas

©2008 Vision Harvest, Inc.

Now that you have the knowledge to use variables and evaluation times in formulas, there is one more thing you need to consider. Your formulas are becoming more complex. Instead of being composed of a single, simple statement, your formulas are going to contain multiple statements. Crystal Reports requires an indicator to tell it where one statement ends and another begins. This indicator is the semicolon “;”. Without semicolons, Crystal Reports treats the entire formula as a single statement. For example, look at the following formula: WhilePrintingRecords NumberVar OrderQuantity If you check the above formula, Crystal Reports displays an error message indicating that, as a single statement, this does not make sense. In order to make these two statements distinct and separate, you must use the end of statement operator, the semicolon. WhilePrintingRecords; NumberVar OrderQuantity; Crystal Reports reads the above statements with no errors. One of the common uses for Evaluation Time functions and Variables are those rare situations when you need to calculate a running total manually. Usually, the automatic Running Total feature does all that you want and does it much more easily than you can do it manually. However, if you ever need to use the results of one running total to calculate another running total, you will find that you cannot do so using the Running Total dialog box. Running totals are available to be used in other formulas, but they are not available to be used in other running total calculations. You are presented with this situation in the following exercise. Remember the Recent Orders with Parameters report you created earlier in the class. That report lists the most recent x number of orders for each employee. You used a running count field and conditionally suppressed the Details section to display a particular number of orders. Now you would like to total the order amounts for those orders. You cannot use the Insert Summary feature because that works during the first pass (before the section is conditionally suppressed) and would total all orders. What you have to do to calculate the total is create a formula with a manual running total that sums the Order Amounts only if the running total Line Count is less than or equal to whatever number you want. (Remember you have a parameter set to let you enter the number of orders you want to see.) You need to create a condition for this running total that is dependent on the value contained in another running total. If you try to do this using the Running Total dialog box, you can see that the {#RT_Line Count} running total field is not available.

91

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

Exercise 5.0 – Try to Create the Order Amount Running Total using Running Totals
1. 2. 3. Open the Recent Orders with Parameters .rpt report and go to Design view Open the Field Explorer dialog box and select Running Total Fields category You are going to try to create a running total called Order Total that will be evaluated based on a formula that indicates the {#RT_Line Count} running total value is less than or equal to the parameter value. Click the New button Name the field Order Total. Then add the {Orders.OrderAmount} field to the Field to summarize box. The Type of summary box should automatically be sum In the Evaluate section, click the Use a formula radio button, then click the button

4.

5. 6.

Look in the Report Fields list. Notice that the {#RT_Line Count} running total is not visible anywhere. You cannot use it to specify the condition on which to base this running total Cancel out of the dialog box and close the Running Totals dialog as well

7.

Since you cannot create a running total based on another running total, you must create the Order Total running total manually, using a variable to hold the sum from record to record. Also, since this formula requires the report be grouped and sorted before it runs, it must run as a Print Time formula. So you have to start it with the WhilePrintingRecords function.

Exercise 5.1 – Use the Evaluation Time Functions and Variables to Create a Manual Running Total
1. 2. 3. 4. 5. Create a new formula called Sum of Orders Expand the Evaluation Time function category. Add the WhilePrintingRecords function by double clicking it Type a semicolon then press ENTER Expand the Variables Declarations category in the Operators list. Add the CurrencyVar x := y operator by double clicking it The Formula Editor leaves the flashing insertion bar right where it needs to be to type the variable name. Type OrderTotal NOTE: The OrderTotal name should have NO spaces Delete the := In this statement you are simply going to declare the variable, not assign a value to it. Move the flashing insertion bar to the end of the line, after the semicolon, then press ENTER Next you want to add an If statement to indicate that if the running total field {#RT_Line Count} is less than or equal to {?Last Transactions} parameter then the formula should add the {Orders.OrderAmount} field to the variable. Look in the Report Fields list. Notice the RT_Line Count field. This is the running total
92

6. 7. 8.

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features
9. 10. Type If then a space, then double click the formula

©2008 Vision Harvest, Inc.

RT_Line Count field to add it to the

Last Transactions parameter to add it to the Type <= , then double click the formula. Type then OrderTotal := OrderTotal + , then add the {Orders.OrderAmount} field to the formula. The final formula should look like the following: WhilePrintingRecords; CurrencyVar OrderTotal; If {#RT_Line Count} <= {?Last Transactions} then OrderTotal := OrderTotal + {Orders.OrderAmount};

11. 12.

Save and close the formula The Sum of Orders formula must be placed in the Details section so it is evaluated for each record in the report. Place the fields after the OrderAmount field and preview the report to see if it is working correctly You should notice the formula works, but is not resetting at each group.

When you create a manual running total, you must reset it manually as well. The reset formula simply declares the variable and assigns it a value of zero. Since this variable is not going to be assigned a value conditionally, you can do the variable declaration and assignment in a single statement. In addition, since variables are Global by default you can use the same variable in another formula by simply re-declaring it.

Exercise 5.2 – Reset a Variable
1. Return to Design view. Create a new formula called Reset. Add the following formula: WhilePrintingRecords; CurrencyVar OrderTotal := 0; 2. 3. 4. Place this formula in the Group Header #1 so the OrderTotal variable resets to zero at the beginning of each group Preview the report to see if the Reset formula works Save the report as Recent Orders with Variables.rpt

93

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

The Sum of Orders formula was placed in the Details section so that it processes each time a new record is evaluated. However, you do not want to see the results after each record. You only want to see the OrderTotal at the end of each group, under the Order Amount column. To do this, create a simple display formula that displays the value currently contained in the variable. The display formula simply spills out the value by re-declaring the variable name.

Exercise 5.3 – Create a Formula to Show the Value in the Variable
1. Create a new formula called Display OrderTotal

2. Add the WhilePrintingRecords function and a semicolon. Then re-declare the CurrencyVar OrderTotal. The Formula should look like the following: WhilePrintingRecords; CurrencyVar OrderTotal; 3. 4. 5. 6. Put this in the Group Footer #1 and format with a top double line top border Finally, you no longer need to see the Sum of Orders or Reset fields. Select them and their titles and suppress them. Run the report to display the last 5 transactions for All Employees during the date range 1/1/2007 to 3/31/2007 Save (Recent Orders with Variables) and preview the report

The report should look like the following example:

94

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

Working with Arrays
In our Parameter fields lesson we learned about creating parameters that hold a range of values or parameters that held multiple values. Crystal stores these multiple values in a structure called an array. An array is simply an ordered list of values that are all of the same data type. The values in an array are known as the elements stored in index positions. For example, an array of number values might look like this: [10, 20, 30, 40, 50] Index 1 has the element value of 10, Index 4 has the element value of 20 Anytime you create a parameter with a range of values or one that allows multiple values, you create an array. For example, in the Recent Orders with Parameters report, you set up a parameter to specify a date range for orders. When you run the report with a beginning date of 01/01/2007 and an ending date of 03/31/2007, you create an array were the first element is 01/01/2007 and the last element is 3/31/2007. The power of the parameter is increased, but how can you indicate in the report the range of dates that it covers? You cannot simply place the parameter on the report because it would only display the first value, 01/01/2007, because it is an array parameter. In the case of a date range parameter, no values are displayed. The solution is to utilize two key array functions that Crystal provides; the Minimum( ) function and the Maximum( ) function. You can use these to pull the lowest and highest values from an array of dates.

Exercise 5.4 – Use Array Functions to Pull Values from an Array
1. 2. 3. Return to Design view To get the values from the array, you need to create a formula. Start a new formula named Display Date Range This formula is going to pull the minimum and maximum values from the parameter, convert them to text, and then concatenate them to some type text. To begin, type in the Formula Editor “For the Period “ then type a + to concatenate Double click the ToText(x,y) function from the Strings function category to add it to the formula Double click the Minimum function from the Arrays function category, then double click the {?Date Range} parameter Move the insertion bar after the comma, then type “MMMM d, yyyy” This argument defines the format for the date when it is converted. Move the cursor to the outside of the closing parentheses, then concatenate and type “ to “ then concatenate again Add the ToText(x,y) function, then the Maximum function. Double click on the {?Date Range} parameter in the x position

4. 5. 6. 7. 8.

95

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features
9.

©2008 Vision Harvest, Inc.

Again, set the format to “MMMM d, yyyy”. The final formula should look like this: “For the Period” + ToText (Minimum ({?Date Range}),”MMMM d, yyyy”) + “ to “ + ToText (Maximum ({?Date Range}),”MMMM d, yyyy”)

10. 11.

Place the formula in Last Transaction text object in the Report Header. resize as needed Save (Recent Orders with Variables) and preview the report

The title should look like the following illustration:

The above exercise makes good use of two Array functions for ranged parameters. The formula created works well as long as the end-user does not select either the No Lower value or No upper value options in the parameter prompt. An example of how the formula behaves when one of these options is checked appears below:

December 31, -4714 is the display value for a zero (null) date. If we were replicate a zero date in a formula it would look like this: Date (0,0,0). Writing a slightly more complex formula solution, utilizing variables would ensure our formula properly deals with this situation. Below is a sample formula that better addresses this issue: StringVar Begin := If Minimum ({?Date Range}) = Date (0,0,0) then “No lower value” Else ToText (Minimum({?Date Range}),”MMMM d, yyyy”); StringVar End := If Maximum ({?Date Range}) = Date (0,0,0) then “No upper value” Else ToText (Maximum({?Date Range}),”MMMM d, yyyy”); “For the Period “ + Begin + “ to “ + End;

96

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

This report also allows the user to input a specific employee, list of employees or all employees. Suppose you want to display the list of employees or the words “All Employees” depending on the user’s choice. If the user selects more than one employee, but not the ALL option, then the values are stored in an array. In order to display the employees, a formula is needed to display them.

Exercise 5.6 – Using a formula to Display the Employees
1. Create a new formula named Display Employee. There are several ways to generate the list to display the employee names. Use the Join function in the String category to create the formula below: If {?Employee Name} = “All” Then “All Employees” Else Join ({?Employee Name},”, “) 2. 3. Add this formula in the Last Transaction text box in the Report Header Run the report selecting All Employees; last 3 transactions and a date range of 1/1/2007 and 3/31/2007. Your report should look like the following:

4.

Run the report again with 5 transactions and the same date range. Change the employee parameter to select Peacock and Suyama as the employees. Your report should look like the following:

97

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

Understanding the Formula Evaluation Time Debugger
Anytime you work with creating formulas in Crystal Reports, there is a risk of having an error in the formula when the report is run. Although Crystal checks the construction of the formula for syntax errors when you save it, some errors occur during the evaluation period as data is extracted from the database. The most common error is a division by zero. This error occurs when a formula containing one object divided by another object containing a zero or a null value. The result is failure of the report to fully execute. In earlier versions of Crystal Reports, when an error such as this occurred, you see the error but it was difficult to determine the error resolution. Often a report contains many formulas; so attempting to locate the error could be tedious. In this version, Crystal displays the Formula Workshop with detailed information if an evaluation time error occurs. The Formula Workshop will display a folder tree on the left side of the screen. The top folder, root folder, provides a description of the error that occurred. The next level in the tree structure provides the names of the formulas that were being evaluated at the time the error occurred. The last level of the tree provides the functions, formulas or fields that are contained in the main formula with the error. Also displayed are the values of each at the time the error occurred.

This Debugger function is critical in assisting you with detecting problems within your reports.

Exercise 5.7 – Add a formula that divides by zero to see the Debugger function
1. 2. Return to the Recent Orders with Variables report Add a formula called Debug Test with the following syntax: {@Display OrderTotal} / 0 In a real situation, you would not intentionally divide by zero. You need to in this example, because this database does not contain fields with zero values.

98

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features
3. 4. 5. 6.

©2008 Vision Harvest, Inc.

Check the formula by clicking the button. Crystal Reports should not detect any errors Place the formula in the Group Footer #1 section. Preview the report. When the report executes, the Formula Workshop displays with details of the error Delete the formula from the report. Save (Recent Orders with Variables) the report and close it

TIP: If a division by zero error occurs in your report, the formula with the error needs to include a test for this condition to prevent the error from occurring again. Use a simple If…Then…Else statement to test for a zero condition. A sample formula would look like the following: If {field 2} = 0 Then 0 Else {field 1}/{field 2}

99

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

Challenge Exercise – Understand and Set Up the YTD Comparison Report
Suppose you need a report that displays a year-to-date sales comparison by category and product. You need to see the YTD quantity sold for each product along with the YTD sales amount. You also want to see the YTD sales amount for last year. Finally, you need to see a comparison percentage of this year’s sales to last year’s sales. The report might look something like this:

To create this report, you are going to use the Categories, OrderDetails, Orders and Products tables. Getting the initial data is easy. You will create groups on the CategoryName field and on the ProductName field. Since you only want order information from the current year (2008) and last year (2007) you must add selection criteria to select only orders greater than or equal to January 1, 2007. To get the YTD Quantity, you need a formula that only displays the Quantity field if the year is 2008 and the month/day of the OrderDate is less than or equal to today’s date. The YTD sales formula displays Quantity times Unit Price under the same conditions. The Last Year’s YTD Sales formula displays the Quantity times the Unit Price if the year is 2007 and the month/day of the Order Date is less than or equal to today’s date. The Percent of Change formula is where you need to use Evaluation Time functions and variables to perform a complex calculation. The formula calculates the percent of change between this year and last year’s sales by subtracting the sum of last year’s sales from the sum of this year’s sales, then dividing by last year’s sales. You could calculate the formula without variables, but variables simplify the formula so it is easier to read and work with. Compare the two formulas listed below and see what you think.

100

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features
The formula without variables:

©2008 Vision Harvest, Inc.

WhilePrintingRecords; if Sum ({@YTD Quantity}, {Products.ProductName}) = 0 then “---“ else if Sum ({@YTD Net Sales}, {Products.ProductName}) Sum ({@Last YTD Net Sales}, {Products.ProductName}) > 0 then “+” + ToText ((Sum ({@YTD Net Sales}, {Products.ProductName}) Sum ({@Last YTD Net Sales}, {Products.ProductName})) % Sum ({@YTD Net Sales}, {Products.ProductName})) + “%” else ToText ((Sum ({@YTD Net Sales}, {Products.ProductName}) Sum ({@Last YTD Net Sales}, {Products.ProductName})) % Sum ({@YTD Net Sales}, {Products.ProductName})) + “%” The formula with variables: WhilePrintingRecords; currencyVar CurrentYTDSales := Sum ({@YTD Net Sales}, {Products.ProductName}); currencyVar LastYTDSales := Sum ({@Last YTD Net Sales}, {Products.ProductName}); currencyVar Difference := CurrentYTDSales - LastYTDSales; If Sum ({@YTD Quantity}, {Products.ProductName})= 0 Then “---“ Else If Difference > 0 Then “+” + ToText (Difference % LastYTDSales) + “%” Else ToText (Difference % LastYTDSales) + “%” Even with variables the formula is complex, but the use of variables makes the formula less difficult to read. The formula creates three variables: the CurrentYTDSales variable contains the sum of the current year’s sales and the LastYTDSales variable contains the sum of the last year’s sales. The Difference variable contains Current Year’s Sales sum minus the Last Year’s Sales sum. The formula then uses a conditional statement to tell Crystal that if the sum of the Quantity is zero to just print dashes. If the current year’s sales is greater than last year’s, then print a + and the percentage. If the current year’s sales is less than last year’s, just print the percentage (the minus sign is added automatically). The WhilePrintingRecords function is optional because Crystal Reports will automatically push this formula to the second pass because it contains summary values. Putting this function in the formula has no negative effect and serves as a notice to the report developer when this formula processes. Now that you know what the report is intended to do, follow the exercise to create it.

101

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features
1. 2. 3. 4. 5.

©2008 Vision Harvest, Inc.

Begin a new report as a blank report. Add the Category , OrderDetails, Orders and Products tables Select only records with an OrderDate greater than or equal to January 1, 2007 Using the Group Expert, group by CategoryName, then by ProductName Add the title, line, logo graphic and Print Date special field to the Report Header and format them like the example at the beginning of the challenge exercise Next, you want to add the formula for calculating the YTD Quantity. This formula does not need an evaluation time function. It will simply process for each record. Create a new formula called YTD Quantity, then type the following formula: If {Orders.OrderDate} in Date (2008,1,1) to CurrentDate Then {OrderDetails.Quantity}

6. 7.

Add this formula to the Details section about three inches from the left Save the report as YTD Comparison.rpt, and then preview it You should be able to see that the quantity does not display unless the date is in 2008 and before or on the current date. For any date that does not meet the condition, Crystal displays a zero. Return to Design view and create a formula for YTD Net Sales. The formula is as follows: If {Orders.OrderDate} in Date (2008,1,1) To CurrentDate Then {OrderDetails.Quantity} * {OrderDetails.UnitPrice}

8.

9. 10.

Add this formula to the Details section after the YTD Quantity formula. Create the Last YTD Net Sales formula. This formula is the same as YTD Net Sales except the year you should indicate is 2007. Here’s the formula: NumberVar LastYear := Year(CurrentDate) - 1; If Year({Orders.OrderDate}) = LastYear Then {OrderDetails.Quantity} * {OrderDetails.UnitPrice} This formula determines today’s year (2008) and subtracts 1 making the LastYear variable 2007. We then compare the OrderDate to the variable and if true, do the calculation. Otherwise, a zero is returned.

11. 12. 13. 14.

Add this formula to the Details section after the YTD Net Sales formula Summarize the YTD Quantity formula using the sum operator for Group #2 The summary field should be in Group Footer #2. Move the Group #2 Name field from the Group Header #2 to the Group Footer #2 Summarize YTD Net Sales and Last YTD Net Sales formulas using the sum operator for Group #2 The summary fields should be in Group Footer #2.
102

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features
15.

©2008 Vision Harvest, Inc.

Now hide the Group Header #2 and Details sections. Preview the report

The report should look similar to the following illustration. The values displayed in the sample will be different than your report due to using the current date as a basis for calculations.

Steps 16 – 21 are all one formula: 16. 17. 18. Now you are ready to add the print time formula. Begin a new formula named Percent of Change Expand the Evaluation Time category in the Functions: list Double click the WhilePrintingRecords function to add it to the formula. Type a semicolon ; and then press ENTER The semicolon separates this function from the rest of the statements in the formula. HINT: The summaries in steps 19 and 21 can be found in the fields list of the Formula Editor and do not need to be typed in. 19. You need to declare two number variables to hold the sum of YTD Net Sales and the sum of Last YTD Net Sales. At the same time that you declare the variables, you are also going to assign them the values. The formula statements look like this: currencyVar CurrentYTDSales := Sum ({@YTD Net Sales}, {Products.ProductName}); currencyVar LastYTDSales := Sum ({@Last YTD Net Sales}, {Products.ProductName}); 20. Now, declare a number variable to hold the difference between the Current YTD Sales and the Last YTD Sales. The formula statement looks like this: currencyVar Difference := CurrentYTDSales - LastYTDSales;
103

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features
21.

©2008 Vision Harvest, Inc.

Next, you need to put in the conditional statement that tells the Formula Editor what to do with the variable values. If the sum of the YTD Quantity formula is zero, then you only want to display dashes. However, if it is not zero, then there is a YTD sales amount and you want to calculate the percent of change by dividing the Difference variable amount by CurrentYTDSales. The % operator takes the place of divide then multiply by 100. You must use the ToText function to covert the calculation to text so you can concatenate it with the % symbol for the display. This is the formula: If Sum ({@YTD Quantity}, {Products.ProductName})= 0 Then “---” Else If Difference > 0 Then “+” + ToText (Difference % LastYTDSales) + “%” Else ToText (Difference % LastYTDSales) + “%”

22. 23. 24.

Place this field in the Group Footer #2 section to the right of the Last YTD Net Sales column. Resize the field so it is smaller and make it bold To check the numbers with the picture below, change the report date to May 28, 2008, with the Report/Set Print Date and Time... command Save (YTD Comparison)and preview the report

The report should look like the following illustration:

All that’s left now is the formatting. 25. Delete the column titles. In the Page Header, place two text objects which say Year-to-Date and Last Year-to-Date. Format the boxes with a background color and center the text in the boxes In the Group Header #1, add text objects for the individual column titles. Format the text so it looks good to you

26.

104

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features
27. 28. 29. 30.

©2008 Vision Harvest, Inc.

Format the Group #1 Name field to be Arial, bold, 14 pt. and colored Format the Group #2 Name field to be Arial, bold, 12 pt. and colored To get the background for the group names, draw a box that surrounds them. Format the box with a background color, but no border. Draw a line to divide the current year information from the last year information The Design view of the report should be similar to the following example:

105

Crystal Reports 2008 Designer 2 Workshop Lesson 5: Using Advanced Formula Features

©2008 Vision Harvest, Inc.

NOTES

106

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

Lesson 6 Using Subreporting as a Workaround Solution

107

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

Lesson Objectives
After completing this lesson, you will be able to: Understand What a Subreport Is Learn how and why you would want to use subreporting Insert a Subreport into a Container Report Combine existing reports to create one report that has all the information you need Link a Subreport to its Container Report Create subreports that link to the data in the main report, so the subreport displays only data related to the current record or group Format Subreports Look at the options available for formatting your subreport Pass a Value from the Main Report into the Subreport Sometimes it is necessary to bring values from the subreport back into the main report. Learn how to use a shared variable to share data from the subreport with the container report Understand How to Link “Unlinkable” Data Using Subreports Link fields with different data type by using subreports in combination with formula fields

108

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

Understanding Subreports
A subreport is a report within a report. You create it in much the same way as you create a regular report. A subreport has most of the characteristics of a primary report, and it can have its own record selection criteria. The only difference between a subreport and a primary report is that a subreport is an object in a primary report and it cannot itself contain a subreport. There are four typical times that you would want to use a subreport: When you want to combine unrelated reports into a single report When you want to coordinate data that cannot be linked otherwise When you want to present different views of the same data in a single report When you want to perform pre-calculations before processing the main report

Unlinked versus Linked Subreports
Unlinked subreports are freestanding reports used within another report. Their data is not coordinated with the data in the primary report in any way. What this means is that there is no attempt to match up the records in one report with the records in the other. Regardless of the underlying data sources, Crystal Reports treats the reports as unrelated. Linked subreports are just the opposite. Their data is coordinated. The program matches up the records in the subreport with the records in the primary report. If you create a primary report with customer information and a subreport with order information and link them, the program creates a subreport for each customer and includes in that subreport all the orders for that customer.

Creating an Unlinked Subreport
To create an unlinked subreport, use the Insert/Subreport command from the menus, or click the Insert Subreport button on the Supplementary toolbar. The Insert Subreport dialog box displays.

109

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

There are two methods to create a subreport. Any existing report can be used as a subreport by simply selecting the Choose a report option in the dialog box. This allows you to locate the report in Windows Explorer and bring its definition into the primary report. You can even use the Report Wizard to create a new report on the fly by selecting the Create a subreport option. Once you have created a report or selected one, click in the container report in the section where you want the subreport to print. Crystal Reports places the subreport in the section in which you clicked. Note the subreport is a separate query so if you place it in the details section it will run for each detail record. When you preview a report with a subreport, Crystal Reports creates an additional tab. Now you have a Design tab for the main report, a Preview tab, and a subreport Design tab labeled with the subreport name.

To simplify the following exercises, we will use a prebuilt report contained in the class files for this course. The report we are going to use is named Sales by Country and it is found in the CR2008 D2 Class Resources\L06 directory. This report contains information for Customers Last Year’s Sales amounts summarized by country. The subreport will contain a chart displaying the top five sales people for 2007.

Exercise 6.0 - Insert a Subreport into an existing Report
1. 2. 3. 4. Open the Sales by Country.rpt report found in the CR2008 D2 Class Resources\L06 directory of the class files resources Insert a new Report Header B section Choose the Insert/Subreport menu item From the Insert Subreport dialog, Subreport tab select the Choose an existing report option and browse and select the Top Sales People for 2007.rpt file. Click Open when finished Since this is an unlinked report, no other options need to be set. Click OK Place the subreport into the Report Header B section at approx. the 3.5 inch position using the horizontal ruler and Preview the report Since the chart would better display beside the country information, format the Report Header B to Underlay Following Sections from the Section Expert Save the report as Sales by Country with Subreports

5. 6. 7. 8.

110

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

The report from the previous exercise should look similar to the following example:

Linking a Subreport
When you link a subreport to a primary report, the program creates the link through the mechanism of a parameter field. When you link a subreport, Crystal Reports: Creates a parameter field in the subreport that relates to the field to which you are linking Creates a record selection formula for the subreport using the parameter field When you preview the container report, Crystal Reports limits the subreport to those records which match the parameter field’s value When you run the report, the program finds the first record it needs and passes the value in the linked field to the parameter field in the subreport. The program then creates the subreport with record selection based on the parameter field value. Here is an example: You create a report that shows customer data and a subreport that shows order data and you link the two reports using the Customer ID field. When you run the report, the program finds the first customer record it needs and passes the Customer ID value from that record to the subreport parameter field. The program runs the Orders subreport. Since the subreport selection formula selects only those records in which the Customer ID value is equal to the parameter field value, and, since that parameter field value is equal to the Customer ID in the first record in the primary report, the subreport contains only those records that have the same customer ID.

111

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

When the subreport finishes, the program goes to the second record it needs in the primary report, prints the customer data, and then passes this customer’s ID number to the parameter field. The program then runs a subreport including only those order records for the second customer. The process continues until the report is finished. All of this parameter field manipulation takes place behind the scenes. You simply pick the fields you want to use to link the primary report with the subreport, and Crystal Reports does the rest. The program passes values to the subreport without the parameter field prompting you for a value. NOTE: If you are in the Design view for a linked subreport and you click the Preview button on the toolbar, the program runs the subreport on its own, without first receiving a parameter field value from the primary report. In this case, the program displays the Enter Parameter Values for Subreport dialog box prompting you for a value. In addition, since the program creates a parameter field, that parameter field is available on the Fields list in the Formula Editors for any other needs you may have for it. TIP: If you need to link fields that are not the same data type, you can do so by creating a formula. This is useful for linking fields that are number data type in one table and a string data type in another table.

Database Links versus Subreports in One-to-Many Situations
When two tables in your report have a one-to-many relationship, the program retrieves the data in different ways depending on the data source, the index situation, the record selection criteria, and whether you are creating a single report based on linked tables or a primary report that contains a subreport. When you are considering whether to use linked tables or a subreport, you need to understand the ramifications of doing it each way. As a general rule, if you have indexed tables, if you are linking on the indexed fields, and if you have record selection criteria based on the indexed fields, the program reads the same number of records whether you are linking tables in a single report or using a subreport. For more in depth information about performance in a one-to-many situation, look up the Crystal Reports Help topic Performance considerations in one-to-many links.

112

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

Exercise 6.2 – Inserting a Linked Subreport into the Container Report
You are now ready to insert the 2008 Quarter 1 Sales.rpt report into the Container report. 1. 2. 3. 4. Make sure the Sales by Country with Subreports.rpt report is open in Design view. Click the Insert Subreport button Click the Choose an existing report option, and then browse to select 2008 Quarter 1 Sales.rpt as the report file Click the Link tab Select the Customers.Country field in the Available Fields: list, then click the > button Crystal Reports automatically selects the Country field in the Select data in subreport based on field: box. Notice the name of the parameter that will be created in the subreport. Note that if you drop down the list of available fields to link to only fields of the same data type are available for selection. 5. 6. Click OK Place the subreport into the Group Footer #1a section. Using the horizontal ruler, position the left edge approx. 1/4 inch from the left margin and size the length to be approx. 3” in length Format the report to look like the example below:

7.

8.

Save the report (Sales by Country with Subreports) and preview the report

The final report should look like the following illustration:

113

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

Formatting the Subreport
Before we look at passing information from the main report into the subreport, let’s look at some of the formatting options available for your subreport. For example, in the exercise we just completed, the Top Sales People for 2007 subreport has a border we do not want. We can use the Format Editor to remove borders. There is also a special subreport tab available for additional formatting:

You can change the name of the subreport so that when you are in the designer mode for the subreport you will see the name you choose here displayed on the tab On Demand Subreports are covered later in the lesson Subreport Preview Tab Caption – allows you to provide a caption for the preview tab. Since it is a formula it can contain database fields as well as text Re-import When Opening – By default when a subreport is incorporated into the main report, any changes to the initial design of the subreport are not updated however if you check this box then changes will be incorporated. This option can be set globally on the Reporting tab under File|Options|Reporting Suppress blank subreport suppresses the subreport including display of title if there is no data

114

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution Exercise 6.3 – Format the Subreport
1. 2. 3. 4. 5. 6. 7. 8.

©2008 Vision Harvest, Inc.

If necessary, open the Sales by Country with Subreports.rpt report From Design, right click on the Top Sales People for 2007 subreport Choose Format Subreport... and remove the borders Click on the Subreport tab and change the subreport name to 2007 Sales Chart Click on the Re-import When Opening check box Save (Sales by Country with Subreports) the report Close the Design tab for the Top Sales People for 2007 subreport Return the container report’s Design tab, right click the 2007 Sales Chart subreport and then select Edit Subreport... Notice the subreport name is now displaying the changes made in step 4

Passing Data from the Main Report into a Subreport
The final report is nearly complete, with one additional task left to perform.. Suppose that the requirements for the report specify a comparison is to be made between quarter 1 2008 sales and last years sales for 2007 in percentage format The easiest method to accomplish this requirement is to pass each country’s 2007 sales data to the subreport for that country using shared variables. To pass values from the main report into the subreport, we use shared variables in a formula. We create a field in the main report with a shared variable set to the value we would like to pass to the subreport. Our formula in the subreport declares the shared variable and then uses it to calculate the field required.

115

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

Exercise 6.4 – Pass the Total Order Amount for the Country to the Subreport
1. In the Sales by Country with Subreports main report create a formula named CountrySales-Main, with a shared currency variable whose value is the sum of OrderAmount by country. The formula text reads as follows: Shared CurrencyVar CountrySales; CountrySales:= Sum ({Orders.OrderAmount}, {Customers.Country}) NOTE: The variable declaration MUST be shared for this variable to be available for use in the subreport. 2. Double click on the 2008 Quarter 1 Sales subreport or right click and choose edit to go into design mode for the subreport. Create a formula named CountrySales-Sub in the subreport that declares the shared variable we just created and uses the shared variable value to create a percentage comparison with the 2008 quarter 1 total. This formula should read as follows: Shared CurrencyVar CountrySales; ToText(Sum ({Orders.OrderAmount}, {Orders.OrderDate}, “monthly”) % CountrySales,2) +”%” NOTE: It is important to make sure the variable name is the same as in the main report formula. Otherwise, Crystal Reports will not recognize the variable being referenced. The formula also converts the percentage value to text to make it easier to work with later on. 3. Create a text box in the subreport’s Report Footer a section. Within parentheses place the CountrySales-Sub formula in to the text box and then add the text “ of 2007”. The text box should look similar to the following:

4.

Save the report (Sales by Country with Subreports.rpt) and Preview the report

The report should look similar to the example on the following page:

116

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

NOTE: Once a report has been added to another report as a subreport, it maintains no link to the original report. However, if you do make changes to the original report, you can re-import it by RIGHT clicking the subreport object and choosing Re-import subreport. You can also set Crystal to re-import all subreports automatically when you open the main report. This command is in the File|Options|Reporting tab.

117

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

Creating On-Demand Subreports
Crystal Reports allows you to create on-demand subreports; that is, subreports that do not show in the main report until the user drills down on them. An on-demand subreport is represented in the main report by an object frame. This reduces the bulk of the main report and makes it easier to manage. In addition, the subreport data is not read from the database until the user drills down to display the subreport. There are two ways to make a subreport display on-demand: When you first insert the subreport, toggle on the On-demand subreport check box in the Insert Subreport dialog box If the subreport is already inserted, right click and select format subreport. Toggle on the On-demand subreport box You can also add an on-demand caption for the subreport by clicking the On-demand Subreport Caption conditional formula button and adding the text you wish to display.

Exercise 6.5 – Create an On-Demand Subreport
1. If necessary, open the Sales by Country with Subreports.rpt report. Return to Design view for the main report. Select the 2007 Sales Chart subreport, and then click the Format button on the Experts toolbar Click the Subreport tab Toggle the On-demand Subreport check box to on button after the On-demand Subreport caption To add a caption, click the command. Type “Click here to see a graph of sales for the top five sales people in 2007”, then save and close the formula and click OK Make sure the subreport is not selected, then save and preview the report Notice that all you see is the caption. 6. To see the subreport data, click the subreport new caption Crystal Reports opens a tab containing the subreport data. What you actually created here is a hyperlink. 7. Save (Sales by Country with Subreports)

2. 3. 4.

5.

118

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

Creating Hyperlinks
You can select any object on a report and create a hyperlink. The hyperlink is saved with the report and is available to other users as a way of viewing additional information. You can create hyperlinks to the following types of locations: A web site on the Internet A file A current field value An e-mail address A current e-mail field value Another Crystal Report file To create a hyperlink field, select a report object, then open the Format Editor and click the Hyperlink tab. Click the type of hyperlink you want to create. Not all hyperlink types are available at all times. The object you select and its location on the report determine which types are available. After you have chosen a hyperlink type, enter the appropriate hyperlink information (the URL of a web site, for example). Once the hyperlink is created, click it on the report to go to the appropriate site, e-mail address or other report. NOTE: If you create a hyperlink to another Crystal Report file, you are creating an on-demand subreport. Just as one subreport cannot contain another subreport, you cannot create a hyperlink between two subreports.

TIP: To select a hyperlink object in Preview view, use SHIFT-click or CTRL-click. Clicking on a hyperlink, without using the SHIFT or CTRL key, activates the link.

Exercise 6.6 – Create a Hyperlink to a Web site
1. Return to Design view in report Sales by Country with Subreports.rpt , then add another Report Header section, Report Header c. Insert a text object with the words “Click Here to Visit My Company’s Web site” With the text object selected Click the Insert Hyperlink button on the Experts toolbar. Select the A Web site on the Internet option and enter the web site www.yourcompany.com and then click OK Format the text to look like a hyperlink i.e. color blue and underline Save (Sales by Country with Subreports.rpt and close the report

2.

3. 4.

119

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

WARNING: When creating hyperlinks, users will not be able to get to the hyperlink if they cannot access the location. For example, if the user does not have the ability to access the internet, then the user will not be able to fully execute the hyperlink. Likewise, if you have created a hyperlink to another report, the user must have permission to access the specified file location.

Using Subreports to Link “Unlinkable” Data
One important reason for using subreports is to link “unlinkable” data. For example, suppose you have a database with additional employee information in it, such as employee benefit. Suppose you need to create a report with Employee related information from the Northwind 2008 sample database along with information from this external data source. If the information resided in one database, then you would simply link the two tables on the EmployeeID field and create the report. However, suppose the EmployeeID field in the Benefits database is a string field (remember that EmployeeID is a numeric field in the Northwind 2008 database). You cannot create this report as a single report because you cannot link fields of different data types. Even when linking a subreport to a main report, the two fields that make up the link must have the same data type, so this might seem to be an insurmountable problem. However, the subreporting feature in Crystal Reports does provide you with an easy solution. Crystal Reports allows you to link to or from formula fields in the main report or the subreport. So you can use a formula field to convert the data to the correct data type, then link from the formula field to the subreport or from the main report to the formula field in the subreport.

120

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

Challenge Exercise – Creating Reports with Linked Subreports
Create a Contact List report that looks like the example below:

1. 2. 3. 4. 5.

First, create the Customer Listing main report. Use the Customers table. Group the records by Country Place into the Details section the CompanyName, ContactName, Phone fields Expand the Group Header #1 section to 1”. Place a text object into the Group Header #1 section with the text Customer Listing Move all of the titles in the Page Header section to the Group Header #1 section under the Customer Listing text box Create a summary field using the count option for the CompanyName field. Place this summary into a text object in the Group Footer #1 section. The text box should look like the following: Total Customers: {Count of Customers.CompanyName}

6. 7. 8. 9. 10.

Format the report like the example above Save the report as Customer Listing.rpt Create a subreport called Supplier Listing using the Supplier table. Group the records by Country Place the SupplierName and the Phone fields into the Details section. Change the text object for the phone column to Telephone Create a summary field using the count option for the SupplierName field. Place this summary into a text object in the Group Footer #1 section. The text box should look like the following: Total Suppliers: {Count of Suppliers.SupplierName}

11. 12. 13. 14. 15.

Delete the Group #1 Name field. Add a text box to the Group Header #1 with the text Supplier Listing. Move the titles in the Page Header to the Group Header Format the report to match the Contact Listing report Save the report as Supplier Listing.rpt. Close the report Return to the Design view of the Customer Listing.rpt report Create an additional group footer (Group Footer #1b) in which to place the subreport

121

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution
16.

©2008 Vision Harvest, Inc.

Add the Supplier Listing.rpt report as a subreport to the Customer Listing.rpt report. Link on the Country field Check to be sure that the link specifies the correct field in the subreport. Place the subreport into Group Footer #1b In both reports, suppress any empty sections to eliminate extra spacing. Also, remove the border on the subreport object You may have noticed that the field titles and text box from the Subreport display even if there are no suppliers for that country. To suppress them, you must format the Subreport and section Group Footer #1b. Right click the subreport and format it to suppress if it is blank. Format the Group Footer #1b section to suppress if it is blank Format the Group Footer #1b to include a page break after each subreport Save (Customer Listing) and preview the report

17. 18. 19.

20. 21.

The example below shows a report page for Brazil:

122

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

NOTES

123

Crystal Reports 2008 Designer 2 Workshop Lesson 6: Using Subreporting as a Workaround Solution

©2008 Vision Harvest, Inc.

NOTES

124

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

Lesson 7 Creating Powerful Groups

125

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

Lesson Objectives
After completing this lesson, you will be able to: Create Custom Groups Instead of grouping on a database field you decide and define your groups Customize Group Sort Order Use a parameter field to allow the user to determine sort order of the groups in the report at run-time Group Selection Select records for display based on group information such as summarized fields Grouping on a Formula Field If you do not have the field you want to group on then create a formula and group on that. This is also useful if you would like the user to decide what field to group on at runtime

126

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

Creating Custom Groups
Suppose you have a report that shows each customer’s last year’s sales. As you scroll through the report, you should notice that you could create groups based on region or country, but that may be too specific. It might be more efficient in this report to have a more general group. A more general group that identifies customers based on a range of sales amounts would make navigating the report easier and finding specific data faster. There is a field that identifies each customer’s Last Year’s Sales. What you really need to do is to specify a range of Last Year’s Sales amounts to identify the groups as mentioned above. Crystal Reports makes this kind of custom grouping easy. You simply have to define the groups in the Insert Group dialog box by using the in specified order sort option. When you select this option, Crystal Reports adds a Specified Order tab to the Insert group dialog box:

Here you can create new groups, give them a name of your choice, and specify values from the data to include in each group. The groups will display in the order they are entered. With the Up and Down buttons you can re-order your specified groups however you want. Once you enter a name for the group and click the New button, Crystal opens the Define Named Group dialog box:

127

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

In this dialog, you use a process similar to the Select Expert to define which values from the field should be included in the group. Once you have defined the custom groups for the report, you can also tell Crystal what to do with any records that are left over using the Others tab.

128

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups
In the Others tab, you have three choices:

©2008 Vision Harvest, Inc.

Discard all others. Crystal eliminates any additional records from the report automatically Put all others together, with the name. Crystal includes any additional records in a single group. Use the Named Group: box to give the group a name Leave in their own groups. Crystal puts the additional records into the report grouping them based on the value in the grouping field. This option gives you flexibility if you only need to change the name of a few values in a field For class you are going to define several customized groups based on a range of Product ID numbers.

Exercise 7.0 – Define Specified Order Grouping
1. 2. Start a new report as a blank report. Add the Customers table. In the Details section, place the CompanyName field, the Country field, and the LastYearsSales field. Click the Insert Group button , drop down the top list and select the {LastYearsSales} field. Drop down the second list and select in specified order. Crystal adds the Specified Order tab to the Insert Group dialog box. Type Gold Customers in the Named Group: box, then click the New button. Our best customers have Last Year’s Sales greater than or equal to $20,000, so you can use the is greater than or equal to operator to define this group. Set the group to be greater than or equal to 20000, then click OK Click in the Named Group: box and type Silver Customers, then click New Set this group to be between 10000 and 19999, and then click OK. The dialog should look as follows:

3.

4. 5.

6. 7.

129

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups
8. 9. 10.

©2008 Vision Harvest, Inc.

Click in the Named Group: box and type Bronze Customers, then click New Set this group to be between 5000 and 9999, then click OK Click the Others tab. All the other customers in this report buy products only occasionally. Click in the text box for the middle option and type Occasional Customers. Then click OK. Enlarge Group Header #1, then move the field titles from the Page Header to the Group Header below the Group Name field. Save the report as Customer Sales.rpt and preview the report. Suppose that you want the Bronze Customers to display first in the report, since these are the customers you need to focus on for increased sales. Return to Design view and edit the Group #1 group. Click the Specified Order tab. Click on the Bronze Customers group name to select it. Click the this group to the top of the list. Click OK. button to move

11. 12. 13.

14. 15.

Save (Customer Sales.rpt) and preview the report. The report should look as follows.

130

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

Customizing Group Sort Order
Groups can be displayed in ascending, descending or original order. This is determined when you create or define your group. However it may be that some users would like ascending and some descending and some original order. You could create 3 almost identical reports to achieve this but Crystal has the ability to determine sort order when the user refreshes the data. You simply need to define a parameter field where the user selects the group sort order for the report. You then use this parameter field in the Insert Group dialog as shown below:

Before using this dialog you need to create a parameter field where the user selects sort order. The parameter would be defined as shown below. You need to make sure the user can not enter their own values. The parameter field dialog would look as follows:

131

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

Next you enter a formula for the group sort order as shown below:

132

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups Exercise 7.1 – Define Group Sort Order
1. 2.

©2008 Vision Harvest, Inc.

Open Monthly Sales by Supplier and Category.rpt and create a String parameter field named Group Sort. Provide the following values for the parameter: “Ascending”, “Descending” and “Original Order” with a default value of “Ascending”; set Allow custom values to False and Prompt With Description Only to True. Right click on Group Header #1 (the SupplierName group) and select Change Group. Click to Use a Formula as Group Sort Order and enter the following formula: if {?Group Sort} = “Ascending” then crAscendingOrder else if {?Group Sort} = “Descending” Then crDescendingOrder else crOriginalOrder

3.

4. 5.

Save the report as Monthly Sales with Group Sort.rpt and refresh the report. Notice you can choose the order of the groups. When finished, close the report.

Using Group Selection to Filter the Records in the Report
The Select Expert can be used to select groups of records in the same way that you select individual records. When you are setting up group selection criteria, instead of basing the selection criteria on standard fields, as you do for record selection, you base the criteria on group name fields or summary fields. If you have grouped your data but have not summarized it, you can only set up group selection based on the group name field. For example, you may want to select only the region Massachusetts. The group selection formula would be: GroupName ({Customers.Region}) = “MA” To use a Group Name field for selection, you must create the Selection Formula from the Formula Editor. From the menu bar, choose Report/ Selection Formulas/Group… The Formula Editor opens for you to create the formula. Warning: Group Selection does not actually limit the number of records pulled from the database. The report still contains all records. The groups that do not match the Group Selection Formula are hidden. Therefore, this may not the best way to select groups from a performance perspective. If you have summarized your data, you can set up group selection based on the summary field. For example, to select only months with a Last Year’s Sales over $5,000, the formula would be: Sum ({@Line Total}, {Orders.OrderDate}, “monthly”) >= 5000 The Select Expert can be used to set up record selection and group selection requests. If you have a summary field selected when you open the Select Expert, the program knows that the selection
133

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

criteria you set up is intended for group selection. In all other cases, the program knows that you are setting up record selection. To set up group selection using the Select Expert, Right click the summary field on which you want to base group selection and choose Select Expert Group… from the shortcut menu. Alternatively, you can open the Select Expert Group without first highlighting a summary field. The Choose Field dialog box appears. Highlight the summary field on which you want to base group selection and click OK. The Select Expert – Group appears with a tab for the summary field. Suppose you want to select only those months that have sales over $5,000. You can use a summary field on the Line Total, and then base the group selection on that summary field.

Exercise 7.2 – Select Only Those Groups with a Monthly Total Sales Greater Than $5,000
1. 2. 3. Return to the Monthly Sales with Group Sort.rpt report. Click on the {@Line Total} summary field in Group Footer #3 (the OrderDate group) to select the field. Right click on the Summary field and choose Select Expert Group… from the menu. The Select Expert -- Group dialog opens with a tab for the Sum of @Line Total summary field. Select the greater than or equal to operator, then type 5000 in the criteria box. NOTE: You cannot drop down the criteria list and see 7000. The list displays individual Line Total values, not summary values. Refresh the data and look through the report. Notice that you do not see any groups with a summary less than $5,000. Notice again that all the group names still display in the Group Tree Navigation area. The groups with less than $5,000 are hidden. Save the report as Monthly Sales with Group Selection.rpt and close this report.

4.

5.

6.

Grouping on a Formula Field
In addition to using a formula to define the group name, you can also create a formula field using the Field Explorer and use it to create a group. This process is useful if you want to let the user define the group at runtime. You can create a parameter to prompt the user for the field on which they want to group. Then create a formula that specifies the field based on the contents of the parameter. You then define the group to use the formula instead of a database field. If this sounds familiar, you are right. It is very similar to what you did in the Customer Phone List report to define the sort options for the report. In fact, you are going to edit that report to use the parameter for grouping instead of sorting.

134

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups Exercise 7.3 – Use a Formula Field for Grouping
1. 2. 3. 4.

©2008 Vision Harvest, Inc.

Open the USA Customer Phone List.rpt report, and then return to Design view. Delete the record selection on phone number. Create a parameter field named Group Parameter. Create a prompt to tell the user to choose a group field. Set default values of Region or City. Your parameter dialog should look as follows:

5.

Create a formula called Group with the following code: if {?Group Parameter} = “City” then {Customers.City} else {Customers.Region}

6. 7.

Click the Insert Group button. Drop down the top list and choose the {@Group} formula. Then click OK. Save the report and rename it USA Customer Phone List with Group Parameter.rpt. Then refresh the data and prompt for new parameter values. Run the report with City selected in the Group Parameter. Crystal groups by the City field. Rerun the report again with Region selected to verify that the grouping is working correctly. When finished, close the report.
135

8. 9.

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

Grouping Hierarchically
You have the option to group data in a report to show hierarchical relationships. When you group data hierarchically, you arrange information based on the relationship between two fields. For example, if you want to show the hierarchical structure of a department, you could group data by the Employee ID and specify the hierarchy using the data field that specifies the Employee’s supervisor, or if you want to view the hierarchical structure of sales offices using the data field that specifies the Regional Sales Office. To group data hierarchically, first insert the group on the field that is the basis of the hierarchy and arrange the group in ascending order. Once the group is created, choose Report/Hierarchical Grouping Options… The Hierarchical Options dialog box appears.

Select the Sort Data Hierarchically check box. In the Available Groups: field list, select the group you want to organize hierarchically. In the Parent ID Field list, select the field by which you want the group organized. Tip: The data type of the field on which you are grouping and the Parent ID field must be the same. For example, they both must be strings (text) or numbers.

Note: The top level of the hierarchy is determined by group instances that match the field on which you are grouping and the Parent ID field. If a group instance is not connected to any Parent ID, it appears at the top of the hierarchy.

136

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups Exercise 7.4 – Create a Hierarchical Group
1. 2. 3. 4.

©2008 Vision Harvest, Inc.

Begin a new report that shows employees with their supervisor information. This report uses the Employees table. Insert a group on the EmployeeID field and sort it in ascending order. You want to customize the group name to include the employee’s name and his/her position. Right click in the Group Header #1 section area and select Change Group. Click the Options tab and then turn on the Customize the Group Name field check box. Click the Use a Formula as Group Name option button, then click the button.

5.

Create the formula that concatenates the FirstName, LastName, a dash and the Title fields. The formula should look like the following when you are finished: {Employees.FirstName} + “ “ + {Employees.LastName} + “ - “ + {Employees.Title}

6. 7. 8. 9. 10. 11. 12. 13.

Save and close the formula. Resize the Group #1 Name field to 3”. Choose Report/Hierarchical Grouping Options The Hierarchical Grouping Options dialog box displays. Make sure the EmployeeID field is selected in the Available Groups list. Click the Sort Data Hierarchically check box. Drop down the Parent ID Field list and select ReportsTo. Type .5 in the Group Indent: box, then click OK. Hide the Details and Group Footer #1 sections and suppress the Page Header section. Make the Group Header #1 section slightly taller. Save the report as Group Hierarchical.rpt and preview. Your report should look as follows:

137

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

One last thing we need to do is to summarize the salary across hierarchical groups. This is part of the summary function that is enabled only when the hierarchical grouping option has been selected.

Exercise 7.5 – Summarizing Across a Hierarchical Group
1. 2. 3. Return to the Design view of the Group Hierarchical.rpt report. Select the Insert Summary button from the Insert menu. Select the Salary field to summarize for Group #1 EmployeeID. Turn on the Summarize across hierarchy function as shown below:

138

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

4. 5.

Move the summary field into the Group Header. Save the report (Group Hierarchical) and preview. It should look as follows:

139

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

Challenge Exercise – Create Customized Grouping
You are going to create a Customer Last Year’s Sales report for customers in the United States. Suppose that your sales force is divided into regions of the country and you would like to group the report by those regions. The only problem is that the {Region} field contains state abbreviations. There is no field that contains regions like Southwest, Midwest, Northern, etc. However, if you know which states belong to each region, you can still group the report by regions. You use the in specified order option in the Insert Group dialog box to specify the regions and which states they contain. 1. 2. 3. 4. 5. Start a new report using the Northwind 2008 database. Choose the Customers table. Insert CompanyName, City, Region and LastYearSales on your report. Insert a record selection to only choose records from the USA. Insert a Group on Region. Drop down the second list and choose in specified order. Create a Pacific group name, then use the is one of operator to add the following states to the region: CA, OR, WA, and AK. Create the following specified groups and include the indicated states: Southwestern: AZ, NM, NV Mountain: CO, ID, MT, UT, WY 6. 7. Arrange the group to appear in the following order: Pacific, Mountain, and Southwestern. Make the Group #1 Name field 14 pt. and resize if necessary. Move the field titles from the Page Header section into the Group Header #1 section below the Group #1 Name field. Insert a summary field on LastYearsSales for the group. Save this report as Regional Sales.rpt. Preview the report. The report should look like the following illustration:

8. 9.

140

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

Challenge Exercise - Using Group Selection
1. 2. 3. Suppose you want each sales rep to be able to view the last year’s sales for his or her region only. Create a parameter that lets the user select a region. Create default values that match the three regions in the report. Also, create a default value for “All Regions.” Do not let the user edit the region names. Set up group selection criteria to display all regions if the user selects the default and only the group with the region name equal to the parameter if the user selects a region. The conditional selection formula for the group name should look like this: if {?Region} = “All Regions” then GroupName ({Customers.Region}) <> {?Region} else GroupName ({Customers.Region}) = {?Region} 4. When finished, save this report as Regional Sales with Parameters.rpt

141

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

Challenge Exercise - Creating a Group Using a Formula
Suppose you need to have a report that prints a customer phone list for all countries. You want the list to be alphabetized and divided alphabetically. For example, you want the report to type an A, and then print all the customers whose names start with A, etc. 1. 2. 3. Create a new report using the Customers table. Add the following fields to the Details section: CompanyName, Phone, City, Region and Country. Resize as needed. Create a new formula that displays only the first character of the CompanyName. The formula should look like the following: {Customers.CompanyName} [1] 4. 5. 6. 7. Insert a group on this formula. Sort the records by CompanyName in ascending order. Format the Group #1 Name field to be Arial Black, size 14. Resize the field as necessary. Save the report as Alpha Customer List.rpt, and then preview it. When finished, close the report. You can easily navigate to the customer you want without having to scroll through the report page by page. The report should look similar to the following:

142

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

143

Crystal Reports 2008 Designer 2 Workshop Lesson 7: Creating Powerful Groups

©2008 Vision Harvest, Inc.

NOTES

144

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

Lesson 8 Working with Cross-Tab Reports

145

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

Lesson Objectives
After completing this lesson, you will be able to: Understand how Cross-Tabs affect your Data Learn what a Cross-Tab is and how to use it best Create a Cross-Tab report Use the Cross-Tab dialog box to easily specify rows, columns and summary fields Format Cross-Tabs Make professional looking Cross-Tab reports by specifying different background colors for columns, rows, and totals, by formatting fields in a Cross-Tab, and by repeating row headers in multi-page Cross-Tabs Create a Chart from a Cross-Tab Use Crystal’s Chart Expert to create graphical summaries of your Cross-Tabs

146

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

Understanding How Cross-Tabs Affect Your Data
A Cross-Tab is an arrangement of fields in a column and row format that makes it easy to identify trends. In using Cross-Tabs, the operative word is by. Anytime you want to identify something by something, a Cross-Tab is an option; for example sales by region, or products by cost or votes by precinct. You can also think of a Cross-Tab as a grid that summarizes values that are grouped in two directions at a time. Sometimes a Cross-Tab can be difficult for people conceptually. An example helps. Suppose you want to determine sales of product categories by employee by month. You can create a report that lists order information, including the employee name and the product category.

This report would contain all the information you want, but it is hard to find specifics and nearly impossible to do any comparisons by month or by employee. You can get more useful information by grouping the report, first by sales person, then by order date (separated by month). Then you can summarize the number of items sold by each employee in each month.

147

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

The information you need is all there in the report, but it is spread out across the pages of the report and is difficult to analyze. Cross-Tabs tend to present data in a more compact, easier to understand format than other types of reporting. In addition, they add column and row totals that make it easy to analyze and predict trends.

Item quantities in this Cross-Tab are summarized by both employee and month together, then totaled for the month and for the employee. Cross-Tabs can be placed in the Report Header or Footer, or in Group Headers or Footers. Where you place a Cross-Tab affects the records that are included in the Cross-Tab. When placed in the Report Header or Footer section, the Cross-Tab object displays summaries for every record in the report. If placed in a group header or footer section, the Cross-Tab displays once for each group, and summarizes only records within the group. Cross-Tabs work quite well in Crystal Reports, however, many users become frustrated when they insert a Cross-Tab into an existing report because it throws off their summary information. Here is a tip to avoid that frustration: TIP: As a rule it is best to only bring Cross-Tabs into reports that have the same record sets or table joins as the main report. If it is impractical to do this, it is also effective to create a CrossTab in a separate report and bring it into the existing report as a subreport. It is important to keep in mind that all Cross-Tabs are complete and separate reports. If the current report is only using the Product table to display Product information then you are only going to get records from that table. However, if you decide to include a Cross-Tab to show the number of products ordered for each supplier, then you need to bring in more tables. The record set is going to grow to include far more than just the contents of the original Products table. It is possible for the number of records to triple. This affects any summaries you had previously created. It is always a good idea to plan reports on paper before you create them in Crystal Reports. Determine which fields will be needed for the Detail section. Decide on the groups that you want to

148

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

create. From this information, determine what tables you are going to need for the report. If a report is going to contain a Cross-Tab object, plan for that as well. Draw a picture of the CrossTab and decide what fields you are going to use in it. If the Cross-Tab requires additional tables and will change the summary values, then you might need to decide upon one of the options mentioned in the tip above.

Creating a Cross-Tab Report
To create a Cross-Tab, choose Insert/Cross-Tab... menu item or click the Insert Cross-Tab button on the Insert Toolbar. You will see a box attached to your mouse cursor – drop it in the report header. Right click on the cross tab object and select Cross-tab Expert... to open the Cross-tab Expert as shown below:

Cross-Tabs resemble spreadsheets in many ways. The data is broken down into rows and columns, and where the rows and columns intersect is a summary value. Fields added to the Rows: and Columns: boxes behave much like groups and are, for all practical purposes, group fields. Fields added to the Summarized Field: box are summaries grouped by both the column field and the row field.

149

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

The elements of the Cross-tab dialog box are listed in the following table:

Cross-Tab Options Option or Item
Available Fields

Description
This list contains report fields and database fields that are available to add to the Cross-Tab. Select a field in the list, and then click the appropriate button to add it to the box you want. You can also drag fields from this list to any of the boxes Rows are fields that display as a group down the Cross-Tab Columns are fields that display as a group across the Cross-Tab Summarized fields are summary fields where the row and column fields intersect Add/Remove buttons. Click one of these buttons to add or remove the selected field from the section. To activate this button, you must highlight a field in the Available Fields list or one of the boxes Like a standard report, you can set group options for the fields in the rows and in the columns. Click the button under rows to set group options for rows and under columns for columns Click this button to change the summary calculation for the selected summarized field. The default summary operation is SUM Clicking this option takes you to the Formula Workshop, where you can create a formula to insert into the Cross-Tab Click this button to edit a formula that already exists in the report. To activate this button, select a formula field from the Available Fields: list This button displays a browse list of data contained in the selected field This button allows you to locate a particular field The Style and Customize Style tabs let you apply formatting to the Cross-Tab. Remember that the data summarized depends on where you have placed the Cross-Tab. Before you create the Cross-Tab, you need to set up a report that lists category sales by employee, and includes a formula called Line Total that is a calculation of the Quantity times the Unit Price fields from the OrdersDetails table. The goal is to insert a Cross-Tab in this report that shows the quantity and amount of each Category sold for each quarter and each month within the quarter.

Rows Column Summarized Field

Group Options Change Summary New Formula Edit Formula Browse Data Find Field

150

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports Exercise 8.0 - Create a Cross-Tab Report
1. 2.

©2008 Vision Harvest, Inc.

Start a new Blank report based on the Northwind 2008 database. Add the following tables: Categories, Employees, OrderDetails, Orders, and Products Use the Select Expert on the Categories.CategoryName field. Choose the is one of operator, then add the following category names: Beverages, Condiments, Meat/Poultry and Produce. Also select for orders placed in 2007 HINT: Use the is between function. Now you are ready to create the Cross-Tab. Click the Insert Cross-Tab button. Drop the Cross-Tab in the report header – you can move it later if it makes sense. Right click in the upper-left corner of the Cross-Tab and select Cross-Tab Expert... You want the CategoryName to be the column heading and the OrderDate to be the row heading. Select the CategoryName field in the Available Fields: list, and then click the button next to the Columns: list button next to

3.

4.

5.

Select the OrderDate field in the Available Fields: list, then click the the Rows: list Select the Quantity field, and then click the list

6. 7.

button next to the Summarized Fields:

Select the New Formula button and create a Line Total formula, which is Quantity times the UnitPrice. Save the formula and then select the formula. Click the button next to the Summarized Fields: list to add it under the Quantity field

8.

You have used a date field in the Rows box to group the data, but you do not want it grouped by individual dates. You want it grouped by Quarters. You need to make a change to the rows group. Select the OrderDate field in the Rows: list and then click the Group Options... button Click the drop-down arrow after the The row will be printed: option

9.

151

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports
10. 11. 12. Select for each quarter and then click OK

©2008 Vision Harvest, Inc.

In Design view, suppress all sections except Report Header Save the report as Category Sales XTab.rpt and then preview the report

Your report should look similar to the sample below:

The Cross Tab above is informative but our goal was to analyze category sales by employee. Let’s do that now. 13. 14. 15. Create a group by Employees.LastName and insert a new section in the Group Header #1 to create a Group Header #1b Move the Cross-Tab into the Group Header #1b Save (Category Sales XTab.rpt). Your report should look similar to the one below:

152

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

Creating a Cross-Tab with Multiple Rows or Columns
The above Cross-Tab is informative, but you wanted to summarize the data by both quarter and month. Crystal Reports lets you add multiple row entries or column entries to create multi-level Cross-Tabs. When you add more than one field to the Rows or Columns section, the Cross-Tab feature subtotals the first field as well as grand totaling for the entire Cross-Tab. To see how this feature works, you are going to add another field to the Rows section. Since you want to summarize by quarter and month, and both are based upon the Order Date field. You will add the Order Date field a second time.

Exercise 8.1 – Create a Cross-Tab with Multiple Rows
1. 2. 3. 4. 5. 6. Click the Cross-Tab to select it, then RIGHT click in the upper left (blank) corner of the Cross-Tab Select the Cross-Tab Expert… from the Shortcut menu Select the OrderDate field from the Available Fields: list, then click the to the Rows: list button next

Select the second OrderDate field in the Rows: section, then click the Group Options... button Click the drop-down arrow after The row will be printed: option, then select for each month Click OK in the Cross-Tab Expert dialog box Notice that there is now a total line for each month, as well as the grand totals for the entire Cross-Tab. In the Design view, select the Row #2 Name object. This is the OrderDate field by month. Format the field to only display the month, by right clicking and selecting Format Field from the shortcut menu Resize the Row #1 Name and Row #2 Name objects to be approx. 1/2 inches in width Save (Category Sales XTab) and preview the report

7.

8. 9.

The report should look similar to the illustration on the next page:

153

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

Applying a Formatting Style to the Cross-Tab
Crystal Reports provides several style templates to apply to a Cross-Tab. The templates are available on the Style tab in the Cross-Tab dialog box. You can select a template, view the results in the sample window, and then apply that template to the Cross-Tab.

154

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports Exercise 8.2 – Apply a Style to the Cross-Tab Grid
1. 2.

©2008 Vision Harvest, Inc.

Return to the Design view and select the Cross-Tab by clicking in the upper left (blank) cell. RIGHT click, and then choose Cross-Tab Expert… Select the Style tab in the Cross-Tab Expert.Try some of the styles by simply selecting the one you want to see in the left-hand list. The sample on the right shows the results of the style. Choose one of the basic formats – that is, one that begins with Basic – Click OK Crystal displays a dialog box asking if you want to apply the style and overwrite any existing formatting changes you have already made.

3.

4. 5.

Click Yes Crystal applies the style to the Cross-Tab. Save the report as Category Sales XTab with Style.rpt

WARNING: When you apply a style to a Cross-Tab, you may lose any formatting that you have done before the style was applied. It is better to apply a style first, and then add custom formatting later.

155

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

Customizing the Cross-Tab Format
Crystal Reports provides powerful formatting features that make Cross-Tabs easier to read and more professional in appearance. The Customize Style tab lets you apply these formats to make modifications to the style you chose.

From this tab, you can: Format the grid lines in the Cross-Tab Format the background color of rows, columns, or grand total rows and columns Suppress empty rows, columns or totals Print Cross-Tabs that span multiple pages and repeat the row headings on each page Modify cell margins Set alias names for row and column dimensions Move row totals to the left or column totals to the top.

Changing Background Colors
You can change the background colors of individual rows or columns by using the Customize Style tab. Just select the column or row heading you want to format, and then select the color you like from the list.

156

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports Exercise 8.3 – Change the Background Color of Rows
1. 2. 3. 4. 5.

©2008 Vision Harvest, Inc.

RIGHT click the upper left cell of the Cross-Tab, then choose Cross-Tab Expert… from the menu. Click the Customize Style tab Select the second OrderDate field in the Rows: section Drop down the Background Color: list and select a color of your choice Now do the same for the Grand Total field in the Columns: section Be sure to choose the same color for the Order Date field and the Grand Total. Click OK Notice the quarter label and the quarter subtotal row are colored the same making them easier to find. Save the report (Category Sales XTab with Style)

6.

Formatting Individual Cells
You can also format individual cells and column and row titles by selecting them and using the Format Editor. Remember that you open the Format Editor by RIGHT clicking on the object you want to format.

Exercise 8.4 – Format Individual Cells and Titles
1. 2. Return to Design view so you can easily see the fields in the Cross-Tab Multiple select all six of the Quantity, Subtotal Quantity and Total Quantity fields. Using the Decrease Decimals button on the toolbar, decrease the decimals to have no decimal places Select and format all six of the @Line Total, Subtotal @Line Total, and Total @Line Total fields to show a fixed currency symbol with no decimals HINT: Use the Format Editor. Select the Quarter row (Row #1 Name) heading and change the font to Arial, 12 pt., bold Modify the Month Date (Row #2 Name) to display the month name as Arial, 10 pt., bold Select all the column and row headings that say “Total” and change the font to Arial, 12 pt., bold Save the report (Category Sales XTab with Style) and preview

3.

4. 5. 6. 7.

157

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports
The Cross-Tab should look similar to the following illustration:

©2008 Vision Harvest, Inc.

Changing the Summary Operation
Suppose you wanted this Cross-Tab to show the average price for the category sold, rather than the sum total. Crystal Reports makes it easy to change the summary calculation being used by the Cross-Tab. All you have to do is RIGHT click on the summarized field you wish to change, and then select Change Summary Operation… from the shortcut menu. Or, if you are in the Cross-Tab Expert dialog box, highlight the summary field you wish to change, and then click the Change Summary… button. Crystal provides access to the same summary operations you have available for grouping.

Suppressing Rows, Columns or Totals
Crystal Reports allows you to suppress the rows or columns in a Cross-Tab or suppress conditionally if those rows or columns are empty. To suppress subtotal rows or columns use the Suppress Subtotal check box in the Customize Style tab. Select the row or column heading, then toggle the check box to display a check mark. Once you have suppressed the subtotals, Crystal automatically suppresses the labels for the subtotal rows by toggling the Suppress Label check box. To suppress Grand Totals or empty rows or columns, use the check boxes for each of the choices located at the lower right corner of the Customize Style tab. In the current Cross-Tab, suppose you want to see the average price for the bicycles and you do not need the column grand totals or the subtotals. Since you are currently summarizing the {@Line Total} formula, and it does not make sense to average that, you need to delete the formula and add the UnitPrice field to the Summarized Fields box.

158

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

Exercise 8.5 – Change the Summary Operation and Suppress the Totals
1. RIGHT click on the upper left corner of the Cross-Tab and choose Cross-Tab Expert… Select the Sum of @Line Total field in the Summarized Fields: list and click the button to remove it 2. 3. Add the UnitPrice field to the Summarized Fields: list With the Sum of OrderDetails.UnitPrice field selected, click the Change Summary... button

4. 5.

Select Average from the Calculate this summary: drop down list Click OK twice Notice that the values have changed to reflect an average price instead of a sum total price. Also, notice that the change altered the formatting. Now that you are seeing averages, you want to suppress all the totals. RIGHT click the upper left cell of the Cross-Tab, then select Cross-Tab Expert… Click the Customize Style tab Click the second OrderDate field in the Rows: section, and then check on the Suppress Subtotal check box Now suppress the Column Grand Totals also. Check on the Suppress Column Grand Totals check box Click OK and save the report as Category Sales XTab Averages.rpt The quarter subtotals and column grand totals do not appear.

6.

7. 8. 9.

NOTE: You did not suppress the Row Grand Totals because you are going to use them to create a chart.

159

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports Repeating Row Heading for Multi-Page Cross-Tabs

©2008 Vision Harvest, Inc.

You may often find that your Cross-Tab reports are wide enough that they span multiple pages. When this happens, it can be helpful to have the row headings repeat at the start of each new page. The Repeat Row Headers check box on the Customize Style tab does this for you automatically. The Cross-Tab on which you have been working fits on a single page so we shall widen the column to see this feature. To see this feature, you are going to reset the paper to print in Portrait, and then turn on the Repeat Row Headers feature.

Exercise 8.6 – Repeat Row Headers for Multi-Page Cross-Tabs
1. Select a summarized field in the cross tab and resize it so that the cross tab goes across two pages. The break in the Cross-Tab table indicates where a page break will occur when printing this report. If you have applied a style template, you may also need to widen the columns to force the cross-tab to print on two pages Open the Cross-Tab Expert… dialog box, then click the Customize Style tab Check on the Repeat Row Labels check box, and then click OK The row labels repeat after the break in the Cross-Tab. Save the report (Category Sales XTab Averages)

2. 3. 4.

Using Alias Names for Column and Row Headings
The Alias for Formulas text box on the Customize Style tab allows you to rename the default dimension names in the Cross-Tab. The dimensions are the column and row names that define which fields or formulas you are grouping on in a Cross-tab. By default, Crystal names these dimensions with the standard {tablename.fieldname} convention. You can use these names in conditional formatting formulas. However, using the default names makes them difficult and time-consuming to type. If you rename them to something shorter and easier to remember, they are much simpler to use in conditional formatting formulas with the GridRowColumnValue function. For example, suppose that you would like to display numbers for each quarter in a different color font to help compare the numbers for each quarter in successive years. You cannot simply change the font color because it changes for all summary fields. You also cannot change based on the value in the Order Date field because the Cross-Tab does not really see the field value. It changes the field name to a dimension name, then uses the dimension for the column title. What you can do is use the GridRowColumnValue function to specify that the conditional format formula should look in the column title Orders.Order Date for the value to compare. However, if you use the default dimension name, the name is long, cumbersome to type and difficult to remember. Which is the Quarter – Orders.Order Date or Orders.Order Date1??? Renaming the dimension makes the formula easier to write. For example, GridRowColumnValue(“Quarter”) is easier to remember and type than GridRowColumnValue (“Orders.Order Date”).

160

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

Once the dimension is aliased, you can use the function to specify the dimension and look within it for a specific value. For example, to print the first quarter in red, you would enter the following formula: If Month(GridRowColumnValue(“Quarters”)) in [1, 2, 3] then crRed So to see how this alias name works, you are going to rename the Orders.Order Date dimension to Quarter, then use that name to make numbers for the first quarter appear in red, for the second quarter appear in blue, for the third quarter appear in lime and for the fourth quarter appear in fuschia.

Exercise 8.7 - Use Alias Names for Column and Row Dimensions
1. 2. 3. RIGHT click in the upper left corner of the Cross-Tab to open the Cross-Tab Expert... dialog box. Click the Customize Style tab Make sure the second Orders.OrderDate field is selected in the Rows: section, then type Quarters in the Alias for Formulas: text box. Click OK RIGHT click on any one of the Quantity fields (the top field in the summary cell), then choose Format Field... Click the Font tab. Click the X+2 button after the Color: drop-down list Enter the following formula, using the Functions list to add the Month and the GridRowColumnValue functions: NumberVar Quarter := Month(GridRowColumnValue (“Quarters”)); If Quarter in [1,2,3] then crRed Else If Quarter in [4,5,6] then crBlue Else If Quarter in [7,8,9] then crLime Else crFuchsia HINT: The GridRowColumnValue and the Column Name is located in the Functions list under the Formatting Functions heading. The Month () function is in the Date/Time category. The colors are in the Color Constants category. The IN operator is used to indicate one of several values as in an array. 5. 6. 7. Check the formula for errors, then save and close the Formula Editor The X+2 button should now appear maroon with a tilted pencil. Click OK and save (Category Sales Xtab Averages) Preview the report The report should look as shown on the next page and each quarter’s numbers should appear in a different color.

4.

161

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

Charting Cross-Tabs
You have already worked with the Chart Expert to create graphs, but charting a Cross-Tab has some additional capabilities. You can choose to chart total figures or individual summary values. When you open the Chart Expert with the Cross-Tab selected, Crystal Reports assumes you want to graph the Cross-Tab. The Data tab in the Chart Expert already has the Cross-Tab button selected.

You can graph on any of the summarized fields and group by either the column dimensions or row dimensions. Also, if you want to display the graph by both column and row dimensions, you can select one in the On change of: box and the other in the Subdivided by: box. For this exercise, you are going to try the chart just by the column dimensions first. Then you will add in the row dimensions to see how it changes the chart.
162

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports Exercise 8.8 – Create a Chart of the Cross-Tab
1. 2. 3. 4. 5. 6. 7. 8.

©2008 Vision Harvest, Inc.

Return to Design view, and then select the Cross-Tab by clicking in the upper left corner Click the Insert Chart button. A chart is placed in the section above the cross tab. Right click on the chart and choose Chart Expert... Select a Bar chart, and then click the Use depth effect option to select a 3-D side-byside bar chart Click the Data tab. On the Show: drop down list select: Avg of OrderDetails.UnitPrice Leave the On change of: as is and change Subdivided by: to None. Click the Text tab Turn off all the Auto-Text boxes. Delete all the text and add the title Average Category Prices Click OK and preview the report Notice the chart only displays one bar for each category indicating the total average price for each product category.

9.

This chart would be more informative if it displayed the average prices quarter by quarter, so you could tell if pricing was going up or down. To indicate this, you can add a feature to subdivide the chart by the OrderDate row dimension. RIGHT click the chart and choose Chart Expert… Click the Data tab Drop down the Subdivided by: list and choose Orders.OrderDate and then click OK To properly label the legend with quarters information, right-click on the chart and choose Chart Options... From the Chart Options dialog, select the Legend tab
163

10. 11. 12. 13.

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports
14. 15. 16. Change the Color Mode: drop list to Color by Series Click OK to close the Chart Options dialog

©2008 Vision Harvest, Inc.

Save the report as Category Sales XTab with Chart.rpt and preview the report

The final Cross-Tab should look similar to the following illustration:

Customizing Cross-Tab Group Names
Since cross-tabs are essentially another way to display grouped information, the process to create customized group names works the same way it does when customizing a group name in a standard report. Suppose you would like to see the chart in this report print 1st Quarter-2004, 2nd Quarter-2004, etc. instead of the numerical month and year in the legend. To accomplish this you must modify the Group Name for Group 1. This will change the Row Name, however, since you have the summary for this group suppressed, it will not display in the cross-tab. You can verify that the function is working correctly by monitoring the legend, or you can unsuppress the subtotal in order to see the new row labels.

Exercise 8.9 – Modify the Group Name with a formula
1. 2. RIGHT click in the upper left corner of the Cross-Tab to open the Cross-Tab Expert... dialog box With the first Orders.OrderDate field selected in the Rows: window, select the Group Options... button. Verify the Cross-Tab Group Options window displays For Each Quarter in the third drop down list
164

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports
3.

©2008 Vision Harvest, Inc.

Select the Options tab, check on Customize Group Name Field option and then select the Use a Formula as Group Name option. Click the X+2 button to enter the Formula Workshop to begin creating the following formula: StringVar Yr := ToText(Year({Orders.OrderDate}),0,””); NumberVar Mo := Month({Orders.OrderDate}); If Mo in [1,2,3] then “Q1/” + Yr Else If Mo in [4,5,6] then “Q2/” + Yr Else If Mo in [7,8,9] then “Q3/” + Yr Else “Q4/” + Yr

NOTE: This formula focuses on the Month and the Year of the Order Date. In order to concatenate the Year portion it must be converted to a text object using the ToText(x,y,z) function. The y position tells the formula how many decimal places to utilize and the z position conveys the thousand separator. 4. 5. Check your formula for errors by selecting the X+2 button. If there are none, save and close the Formula Workshop and click OK twice to return to the report to preview You will notice the Chart legend has reverted back to not showing Quarter information. You must once again change the Legend Color Mode using the Chart Options dialog. Do so now before saving the report Save your report (Category Sales with Chart) and preview the results. The report Preview should look like the sample below:

6.

165

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

CurrentFieldValue
You may wish to conditionally format cross-tab cells based on their value. In our example we may want to highlight a value when the average order amount is greater than $1,000. Typically with conditional formatting we select the field and add our conditional formatting. However the cross tab cells do not contain database fields but summary values. To conditionally format cross tab cells we use the function CurrentFieldValue. As its name suggests, this function contains the current value in a cell.

Exercise 8.10 - Use CurrentFieldValue to highlight values.
1. RIGHT click in the upper left corner of the Cross-Tab to open the Cross-Tab Expert... dialog box. Click the Style tab. Select from the style list, the Original style and then OK. You will be warned that all custom formatting will be lost. Click Yes to the warning message Select the Avg of OrderDetails.UnitPrice in the Total column and right click to obtain the shortcut menu. Select Format Field... Select the Border tab and click on Background to turn this option on, then click on the X+2 Formatting button for the background color drop list In the Formula Editor type the following: If CurrentFieldValue > 20 then crRed Else crNoColor The CurrentFieldValue function is found in the Formatting category in the function list. 5. Save the report (Category Sales with Chart) and preview the report. The final Cross-Tab should look similar to the following illustration:

2. 3. 4.

166

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

167

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

Challenge Exercise – Cross-Tab Reports
To practice with Cross-Tabs, you are going to create a report that compares customer sales by country and region and date. First, create the report. 1. 2. 3. 4. 5. Start a new blank report using the Customers and Orders tables Set the Page Orientation to print Landscape under File|Page Setup Select only those records in the countries of Canada, Mexico, and the USA. Group by Country Save the report and name it North America Sales by Country and Year.rpt Now you are ready to insert the Cross-Tab that shows how high the sales are for each country, region, year and quarter. Click the Insert Cross-Tab button on the toolbar. Place the Cross-Tab in the Report Header and right click in the upper left-hand corner, select the Cross Tab Expert... Specify the Country field and the Region field as rows. Specify the OrderDate field as the column dimension and group it by year. Specify the OrderDate field again as a column and group it by quarter. Indicate the OrderAmount field as the summarized field Format the Cross-Tab with a style, then edit the style to display a different color for the subtotal rows for the Country Make sure the Row Labels are repeated on page 2, Click OK when finished Conditionally format the Cross-Tab so it displays summary fields in three different font colors for the three years HINT: First, add an Alias for Formulas to the top OrderDate column (year). Then conditionally format the font color with the following formula: (use any colors you like) If Year(GridRowColumnValue (“Year”)) = 2006 then crOlive Else If Year(GridRowColumnValue (“Year”)) = 2007 then crPurple Else crRed 10. Format the cells of the Cross-Tab so that if the OrderAmount is > than 5000 the background is silver HINT: use conditional formatting and current field value as shown below: If CurrentFieldValue > 5000 then crSilver Else NoColor 11. Create a 3D bar chart that displays the OrderAmount by year, subdivided by Country. Crystal Reports will add a Report Header section (RHa) and place the chart in that section. Save and preview the report. It should look like the illustrations on the following page Save (North America Sales by Country and Year) and close the report when finished

6.

7. 8. 9.

12. 13.

168

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports
The graph of the Cross-Tab:

©2008 Vision Harvest, Inc.

The Cross-Tab page 1:

169

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports
The Cross-Tab page 2:

©2008 Vision Harvest, Inc.

170

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

NOTES

171

Crystal Reports 2008 Designer 2 Workshop Lesson 8: Working with Cross-Tab Reports

©2008 Vision Harvest, Inc.

NOTES

172

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts

©2008 Vision Harvest, Inc.

Lesson 9 Report Alerts

173

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts

©2008 Vision Harvest, Inc.

Lesson Objectives
After completing this lesson, you will be able to: Create multiple sections Expand your formatting power by learning how to add sections to the report Understand Report Alerts Understand what a report alert is and when to use one Create Report Alerts Learn how to set up a report alert and use it in a report Use Report Alerts with Parameters Learn how to conditionally establish a triggered alert with an input value into a parameter field Create Formulas based on Report Alerts Generate formulas that calculate or control formatting options based on triggered alerts Identify Creative ways to use Report Alerts Use Report Alerts as a form of data analysis by creating queries against saved data

174

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts

©2008 Vision Harvest, Inc.

What are Report Alerts
In today’s busy, data-driven business world it is not surprising to see many reports focused on identifying problems or conditions which are outside the norm. This type of report is referred to as an exception report and is very useful at helping report viewers quickly get to the key indicators they need to make better decisions. Now all reports can offer exception reporting through a feature called Report Alerts. Report Alerts are custom messages that appear when certain conditions are met. Some possible uses are: A daily report summarizes all customer orders for the day and the sales manager needs to know when an order by a key customer cannot be fulfilled The accounting department at a manufacturing plant runs a biweekly payroll report detailing the next payroll and also wishes to be alerted if payment for over-time exceeds regular pay by 3% or more A key management report is run weekly which identifies 50 Key Performance Indicators (KPI) of the company’s financial well-being. Five of these KPI’s are considered mission-critical and top management needs to be informed immediately if any of these five indicators fall outside their “safe” range A weekly sales report summarizes all sales reps’ actual sales against their sales goals. The sales manager wants to be notified whenever someone either exceeds or is severely short of their goal Report Alerts are the first step towards pushing reports to wireless devices since they are small in nature and are meant to get our attention rather than perform lengthy data analysis. Business Objects has web-enabled Report Alerts with their Enterprise application and now Alerts can be viewed from a mobile device.

175

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts

©2008 Vision Harvest, Inc.

Creating Report Alerts
There are three steps to creating a Report Alert: Name the Alert Define the condition which triggers the Alert Create the message that appears when the Alert is triggered (Optional) To create a Report Alert, click the Report menu and choose Alerts|Create or Modify Alerts. The Create Alerts dialog box opens.

Click the New button and the Create Alert dialog box opens.

You can now name the alert. Type in your message and then click the condition button, which opens the Alert Formula Editor, to provide the conditions for the alert. If you don't want the same message all the time, you can provide a conditional message as well.

176

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts
Keep in mind the following when creating your Alert condition:

©2008 Vision Harvest, Inc.

Alert formulas can be based on recurring records or summary fields, but they cannot be based on print-time fields, running totals, or print time formulas. Also Alert formulas cannot have shared variables If an Alert formula is based on a summary field, any recurring fields used must be constant over the summary field you are using Alert formulas can use either Crystal Syntax or Basic Syntax To see how Report Alerts work, you are going to edit the Monthly Sales by Supplier and Category report that you created earlier in class. Suppose you want to be alerted to any suppliers who placed fewer orders than normal for the year. You will need to create a summary field that counts the number of orders for each supplier. This summary field will be the basis of the Report Alert condition. You want to know when this total is less than 30.

Exercise 9.0 – Create a Report Alert
1. 2. 3. 4. 5. 6. 7. 8. 9. Open the Monthly Sales by Supplier and Category.rpt report. Add a summary on the Order ID field to the Group Footer # 1 that performs a count of the Order ID field. Move the summary field to the right so that you have room to place a label in front of it that says # of orders: In the Report menu, choose Create or Modify Alerts. Click the New button on the Create Alerts window. Type Low Order Count for the name. The message will be: There are suppliers who placed fewer than normal orders for the year. Click on the condition button. This opens the Alert Condition Formula Editor. The condition formula is: Count ({OrderDetails.OrderID}, {Suppliers.SupplierName}) < 30 10. 11. 12. Save and close the formula condition. Then make sure the enabled box is checked and click OK. Click the Close button on the Create Alerts window and save the report as Monthly Sales by Supplier and Category with Alerts.rpt Refresh the report. The Report Alerts window should pop-up because the alert was triggered. You can click on the View Records button to see which suppliers placed fewer than 30 orders. Clicking View Records will show those records on their own tab named Low Order Count.

177

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts

©2008 Vision Harvest, Inc.

13.

Close the report when you are finished.

Exercise 9.1 - Using Report Alerts with Parameters
The goal in this exercise is to create an Alert for Regions whose total sales is above the user specified amount entered via a parameter. 1. 2. 3. Begin a new report as a blank report. Add the Customers and Orders tables. Group by Region. Select only records with Order Dates in 2007. You also only want to see those records that are for customers in the USA. Do this by adding another data filter for the Customers.Country field. Add a title that says: 2007 Regional Sales. Format the title however you like. Add the OrderID, OrderDate, and OrderAmount fields to the Details section. Summarize the OrderAmount field using the Sum summary operator. Resize the Group #1 Name field to be about 1’’ wide and then move it from the Group Header #1 section to the Group Footer #1 section. Move the column headings from the Page Header section to the Group Header #1 section. Suppress the Page Header section. Hide both the Group Header #1 and Details sections. Create a parameter field called Sales Threshold. Specify a number type. Enter the following prompting text: Enter the $ amount of your Regional Sales Alert level. Regions with sales over this amount will trigger a Report Alert. Create a Report Alert called Regional Sales Level Alert. Type in the message: The following Regions exceeded your sales level threshold. For the condition, you want the Alert triggered when the Regional summary is greater than your parameter entry: Sum ({Orders.OrderAmount}, {Customers.Region}) > {?Sales Threshold} 11. Save the report as Regional Sales Alert.rpt and preview the report. Enter 15000 for the parameter prompt. Click view records to see which Regions exceeded $15,000 for total sales. You should see ID, NM, and OR.

4. 5. 6. 7.

8. 9.

10.

Basing Report Formulas or Conditional Formatting on Report Alerts
While the dialog of showing Report Alerts having been triggered is useful you may also want to incorporate information into your report about the Alerts and if they have been triggered. There are three functions in the Crystal Reports Formula language that support Alerts as follows: IsAlertEnabled: Returns the value True if the Alert enabled check box is checked otherwise it returns False IsAlertTriggered: Returns True if the record the formula is evaluating triggers the alert
178

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts
otherwise it returns False

©2008 Vision Harvest, Inc.

AlertMessage: Returns the message that was typed into the Message box or the results of the Message string formula

Exercise 9.2: Use the Alert Functions in Your Alert Report
1. Open the Regional Sales Alert.rpt report and create a formula named AlertTriggeredMessage in the Group Footer that displays a message if the region triggered the alert. Your formula should read as follows:

2.

3.

Save your report (Regional Sales Alert) which should look as follows:

179

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts

©2008 Vision Harvest, Inc.

4.

Now let’s conditionally format the Group Footer to have a silver background if the alert is triggered. Using the Section Expert enter the following formula: If IsAlertTriggered (“Regional Sales Level Alert”) Then crSilver Else crNoColor Your report should look as follows:

5.

Save and close the report.

Creative Usage for Report Alerts
Report Alerts were created as a way to identify exception reporting. Although this was the original basis for this function, there are additional ways to use this key feature to enhance your reporting process. One idea you might consider is to use Report Alerts as a means to query a saved data set. Once you have run a query against the database, you may need to see different data segments. This generally requires that you rerun the report with different parameters or it may even be necessary for you to have multiple reports to manage. The main benefit of having the ability to query saved data within a report is that you can view different slices of the data output without having to rerun the report against the database. This saves you valuable time that you would normally spend populating parameters and refreshing the report, as well as relieving unnecessary queries on the database server. Your database administrator will definitely appreciate the reduced stress load on the server! To see how this process works, consider the following: Suppose you are the manager of a product fulfillment center and you have a Order Tracking Report that you use to monitor orders that have been received during 2007. You have several additional reports that retrieve the same data with the exception of a few data restriction elements. Currently you have the following reports that you manage on a daily basis: Order Tracking Report Domestic Shipping Report International Shipping Report Days to Ship Report
180

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts

©2008 Vision Harvest, Inc.

Imagine how long it would take to run all of the daily reports required to do your job, if each report took 20 minutes to process. What if using Report Alerts could produce all of the data segments in one report?

Exercise 9.3: Create the Order Tracking Report
1. Begin a new report, as a blank report, based on the Northwind 2008 database and the Customers, Orders and Shippers tables. Verify that the link was created between the Customers and Orders tables on the CustomerID field, and between the Orders and Shippers tables on the ShipperID field. Using the Select Expert option set the OrderDate field to only retrieve records for 2007. Modify the page orientation to Landscape by selecting File>Page Setup. Add the following fields to the details section of the report: OrderID, OrderDate, OrderAmount, Customers.CompanyName, ShippedDate, and Shippers.CompanyName. Change the Customers.CompanyName label to “Customer Name”, and the Shippers.CompanyName label to “Ship Via”. Create a formula named Days to Ship using the following structure: {Orders.ShipDate} - {Orders.OrderDate} Add the formula to the Details section after Shippers.CompanyName 7. 8. 9. Add a text object to the Report Header with the text Order Tracking Report. Format the text box so it looks good to you. Format all of the date fields to display the date only. Save the report as Order Tracking Report.rpt and preview your results. The report should look similar to the sample below:

2. 3. 4.

5. 6.

181

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts Exercise 9.4: Use Report Alerts to Query Saved Data

©2008 Vision Harvest, Inc.

You are now ready to create the Report Alerts. You will create three individual alerts that will allow different slices of the data to display. The alerts will query the saved data set, so there will only be one query sent to the database. 1. 2. 3. Return to the Design view of the report. Select the Report>Alert menu option. Select the Create or Modify Alerts option. Create a Report Alert by selecting the New button. Name the alert Domestic Shipping Data. Verify that the Enabled option is checked and select the Condition button. Use the following formula for the condition: {Customer.Country} = “USA” 5. 6. Save and Close the Formula Workshop and then select OK to return to the Alert listing. Create a new alert titled International Shipping Data where the formula for the condition is: {Customer.Country} <> “USA” 7. Create a new alert titled Days to Ship Greater than 10 Data where the formula for the condition is: {@Days to Ship} > 10 8. Close the Create Alerts window and Refresh the report. The following window will display:

4.

182

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts
9.

©2008 Vision Harvest, Inc.

Select the Days to Ship Greater than 10 Data alert and then the View Records button. Your Preview should look like the following:

Clicking on the Preview tab will re-display the Report Alerts dialog box. You can then select a different alert and click the View Records button or click Close to display the normal report with all records. 10. Save (Order Tracking Report) and close the report.

183

Crystal Reports 2008 Designer 2 Workshop Lesson 9: Report Alerts

©2008 Vision Harvest, Inc.

NOTES

184

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

Appendix A Report Templates

185

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

Lesson Objectives
After completing this lesson, you will be able to: Describe a Report Template Understand what a report template is and when to use one Use the Template Expert Use the templates provided with the template expert; browse for to use a report and add templates to the template expert Create your own Template Learn about template fields and how to use them to create a template Template Considerations Understand the limitations and unpredictable nature of templates

186

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

What is a Report Template
A report template is a predefined file that contains formatting when it is applied to a report. In earlier versions of Crystal Reports, you could pre-format a report using styles. The styles would format a report with pre-determined colors, fonts, font sizes, etc. However, as a report designer you could not create your own styles. Styles have been replaced with templates in the previous version. Templates have more functionality than styles. Most importantly, you can create your own templates. A template enables you to have total control over the look and feel of your reports. It also allows you to apply consistent layouts for the reports throughout your company.

Standard Report Creation Wizard and Templates
Report Templates have to be applied to a report. This can be done during the report creation process of the Standard Report Creation Wizard. As you are guided through the wizard steps, you will come to the Template dialog. This is an optional function. You will notice that the window is divided into two sections. The left side of the window lists all of the available templates with a preview of the format layout being displayed on the right in the preview window.

By default, templates are not automatically applied to reports. You must select a template from the list. However, after reviewing the template previews, you may decide that the layouts are not exactly what you are looking for. Crystal provides you with the option of using an existing report as a template. By selecting the Browse button, Crystal will direct you to the file directory where you can select a report that you have created in the past for use as a template. You will notice, however, that there is not a preview option for the report. The preview and template description have to be configured in the original report you are using as a template before accessing it through the Browse option. This information can be set up in the Document Proper187

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

ties dialog box of any report. The Document Properties dialog box is accessed from the File/Summary Info menu option. Notice the information on the Summary Tab. In order to have a preview, the Save Preview Picture option must be selected. Likewise, if you want a template title to display, it has to be entered into the Title text box.

Note: You would expect the template field to be the title shown in the template preview but that is not the case.

Tip: If you browse and use your own report for the template it won’t appear in the list of templates next time you use the wizard. If you want one of your reports to be listed as a template then you need to place it in the \ProgramFiles\Business Objects\Crystal Reports 12.0\Templates directory. If you wish to change this location then you must change the Registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Business Objects\Suite 12.0\CrystalReports\Templates\ TemplatePath.

Exercise 10.0 - Apply a Template to a Report using the Standard Report Wizard
1. 2. 3. 4. 5. Create a new report using the Standard Report Wizard. Select the File>New>Standard Report menu option. Select the Customers table in the Northwind 2008 database and then click Next. Move the CompanyName and LastYearsSales fields into the Fields to Display: list and then click Next. Group on the Region field and then click Next. The Summaries dialog box should automatically include a summary on the

188

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

LastYearsSales field. Make sure that it is and then click Next for the Group Sorting dialog. 6. 7. 8. 9. Click Next for the Chart dialog. Click Next; in the Record Selection dialog box, select records for the USA only based on the Country field and then click Next. In the Template dialog box, select the Corporate (Green) template and then click Finish. Save the report as Standard Expert.rpt. Your report should look as follows:

Note: Even though you chose not to have a graph, your report now has one since a chart is part of the template. Of course you can right click on the chart and delete it.

189

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

The Template Expert
More often than not you may not use the Report Wizard or you already have a report created but still want to apply a template. In this case you would use the Template Expert. You can access the Template Expert from the Report menu or by clicking on the template expert button on the Experts toolbar. You will see the following dialog:

Notice the only difference from the template tab in the Wizard is you have the option to undo the current template or re-apply the last template. These options are only available within the Crystal Reports session.

Applying a Template and the consequences
When you are working with a report that has been completed manually, you must be mindful of the existing data layout within the report before applying a template. Depending on the layout, a template may not work properly because of the data elements. This means you must also be aware of the required elements needed for a template to work. To see the consequences of applying templates without the proper elements, open the USA Canada Sales.rpt. The report in its current state looks like the following illustration:

190

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

Now look at the report after the Corporate (Blue) template has been applied:

191

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

Notice that the report does not display a chart as indicated by the template. There is not a chart because the template expert could not work out which fields the use because the summary values placed at the bottom of the report are conditional running totals. However, you will notice that the expert did create the space in Report Header c for the chart. If the template does not work out the way you intended it, Crystal Reports allows you to undo the template. If you return to the Template Expert, you can select Undo the Current Template to return the report back to it’s original form. To get this report to work properly with the Corporate (Blue) predefined template, it must be adjusted. First, a group on Country must be added as well as a summary on Last Year’s Sales. Otherwise, the report will not have the necessary values to chart. With these changes, the report should look like the following illustration:

When the same Corporate (Blue) template is applied, the report now displays different results.

192

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates Exercise 10.1 – Applying your own report as a template
1. 2. 3. 4. 5. 6. 7.

©2008 Vision Harvest, Inc.

Create a report using the Customers table in the Northwind 2008 database. Add the CompanyName and LastYearsSales fields to the Details section and group the report by the Region field. Select records where the Country field is equal to USA. Add a text box to the Report Header with the words “USA Customer Last Year’s Sales”. Add a border on the text object with a drop shadow. Size the font at 18pts. Insert a Count summary on CompanyName and a Sum summary on the LastYearsSales fields for each region. Add a pie chart to the report showing the sum of LastYearsSales for each region. Save the report as Template Customer.rpt. Your report should look as follows:

193

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates
8.

©2008 Vision Harvest, Inc.

Close the report. Start a new report against the Customers table and simply place CompanyName and LastYearsSales fields on the report. You will have a simple listing report. Click the Template Expert button to open the Template Expert. Click the Browse button and select the Template Customer.rpt report as a template for this report, click Open and then OK to apply the template. Your report should look as follows:

9.

Note: The large Report Header a is created for a chart but there were no summary count fields in the receiving report so no chart was created. The record selection from the template is not applied – a template is simply a formatting tool. 10. 11. Summarize LastYearsSales by Region and limit records to the USA only. Insert a Count summary on the CompanyName for each region and reapply the template. You will see a chart of the count of customer i.e. only a chart on the first summary field. Save report as Customer Template Applied.rpt.

12.

194

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

Note: Notice that each time you have to browse for the report; later we shall look at adding a report to the template directory.

Warning: Templates are unpredictable so make sure you save your report before applying a template. Even though you can undo up to one level if you are using the template expert it’s better to be safe.

Template Considerations
Creating and applying templates forces you as the report developer to take into consideration those items affected when a template is applied and those objects that are remain unaffected. Regardless of those considerations, it is a very good rule of thumb to save the report before applying a formatting template. By saving the report, if you apply several templates to the report and do not get the desired results, simply closing the report without saving the changes is the easiest way to return to the original report. The chart listed below outlines those items affected if an existing report is used as a template and applied to a new report. Template Object Considerations New Report Objects Formatted New Report Objects NOT Formatted from Template from Template Fields Group Names Group Charts Summary Fields Hyperlinks Bitmap Images Lines, boxes, borders Static OLE objects Detail Charts Subreports OLAP grids Cross-tabs or Maps Embedded OLE objects BLOB fields Specified order grouping Advanced summaries such as Top N, Percentages and Running Totals

Tip: For more information on what items are affected in the target report from the template, refer to the Template Considerations section of the Crystal Reports Help File.

195

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

Creating Your Own Templates
So far we have looked at using an existing report as a template. Suppose you would like to create a few of your own templates with your own look and feel with a company logo and etc. A new additional feature with templates is the Template Field. A Template Field is a placeholder for a report object and does not contain any data. When we create templates we can create reports without any connection to an underlying database.

Inserting Template Fields
To create a template, you must first begin a new report without a database connection. From the Insert menu option, you will notice in the drop down list an option to add a Template Field Object. This is the object you need to use to add a template field to the report. By utilizing template field objects instead of fields tied to the database, you gain a lot of flexibility in formatting the objects for any possible data type that may populate the column when the template is applied to a report. Keep in mind that template field objects must represent result based fields such as those database fields, parameter fields, SQL statements, and formulas. Special fields such as page numbers must be placed onto the report template from the Special fields category. When you select the field for entry you will see the following in your design window:

Notice that you have a detail entry to format and a column heading. Also notice that the template field is actually a formula field. If you preview this report you will see the following:

196

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

There is no data associated with this template report so you will not see any data. You can add as many template fields as you would like.

Formatting Template Fields
You format a template field just like any other field, however, you will notice that when you right click on the template field and choose to format it, all the format options are available.

You will not know what the data type of the field will be so make sure all the formats are set to cover any type of field. This example template field in the details section will format the first database field in the details section.

Giving Template Fields a Value
It is kind of tricky to visualize the formatting of template fields since there is no data to see in preview. By default a template field has the value Space(10). However, as mentioned earlier a template field is a formula field so you can give it a value to see the formatting. Any created template fields can be found in the Field Explorer.

197

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

Simply select a template field and choose to edit it. Tip: Give each template field a different data type so you can preview all formatting from within your template. For example the first template field may have the value “abcdef” showing how text fields will format; the second template field may have the value 9999.99 so you can see how a numeric field is formatted and the third template field may have the value CurrentDateTime to see how a date/time field formats. The formula for the first template will look like: //Crystal Report Template Field WhileReadingRecords; Space(10); “abcdef” Here is a preview of a report with 3 template fields with the values set as discussed above.

198

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

Exercise 10.2 - Creating a Template Report with Template Fields
1. 2. 3. 4. Start a blank report with no database connection Add three template fields to the Details section. Format the column headings to all be Arial 12 bold without an underline. You may need to resize the text objects. Format the template fields in the Details section to have no decimal places if the report object is a number and to have a fixed currency symbol and be a date of the format March 01, 2003 if a date/time field. Insert the Special Field Report Title into the Report Header and format it to be size 16, bold italic with a border that has a drop shadow. Stretch the box the width of the report and center the text. Resize as needed. Insert Page Number in the Page Footer on the left hand side and Print Date on the right. Complete the Summary Info with a name for your template in the Title: box and click to save a preview picture. Your Document Properties dialog should look as follows

5.

6. 7.

8.

Save the report in the C:\Program Files\Business Objects\Crystal Reports 11\ Templates\en as Template Report. The design and preview windows should look as follows:

199

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

9.

Start a new report on the Employees table and do an employee listing with the LastName, HireDate and Salary fields in the Details section. Under File|Summary Info add a Report Title: “Employee Salary Listing”. Let’s preview this report before we apply our template – your report should look as follows:

10.

Notice that the date is formatted as a date/time; the salary field has 2 decimal points; the column headings are not bold and there is no title.

200

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates
11.

©2008 Vision Harvest, Inc.

Now select the Template Expert from the Report menu. You should see your template listed and notice a preview when you select it as shown below:

Select to apply your template and your report should look as follows:

12.

Save the report as Employee Salary Listing.rpt and close.

201

Crystal Reports 2008 Designer 2 Workshop Appendix A: Report Templates

©2008 Vision Harvest, Inc.

NOTES

202

Crystal Reports 2008 Designer 2 Workshop Appendix B: The Northwind 2008 Database

©2008 Vision Harvest, Inc.

Appendix B The Northwind 2008 Database

203

Crystal Reports 2008 Designer 2 Workshop Appendix B: The Northwind 2008 Database

©2008 Vision Harvest, Inc.

The Northwind 2008 database used for class is a Microsoft Access database file accessed through the Access/Excel (DAO) connection method. The tables used in class for this database are listed above. Lines between tables indicate where links can be created between the tables. There may be other linkable fields between tables. This illustration shows the most likely ones.

204

Crystal Reports 2008 Designer 2 Workshop Appendix B: The Northwind 2008 Database

©2008 Vision Harvest, Inc.

NOTES

205

Crystal Reports 2008 Designer 2 Workshop Appendix B: The Northwind 2008 Database

©2008 Vision Harvest, Inc.

NOTES

206

Crystal Reports 2008 Designer 2 Workshop Appendix C: Installation and System Requirements

©2008 Vision Harvest, Inc.

Appendix C Installation and System Requirements

207

Crystal Reports 2008 Designer 2 Workshop Appendix C: Installation and System Requirements

©2008 Vision Harvest, Inc.

Installing the Application
Crystal Reports provides a step-by-step process to install the application to your system. When the installation disk is placed into the CD tray of your system, the application will automatically begin installing providing the auto play feature has not been disabled on your PC. If this feature has been disabled, locate the setup.exe file to begin the installation process. During the installation, your system will be scanned for outdated files. You will be prompted to update these files with the ones provided. During the installation, the operating system of your PC will be detected. If Crystal Reports requires an updated version of your operating system, you must first update before the application will install. (See section below for the supported OS.) Once you have entered your key code and accepted the license agreement, you will be prompted to select the type of installation you would like to perform. Crystal Reports provides Typical and Custom installation options. A Typical installation will install the primary components of Crystal Reports, such as the report designer. A Typical installation does not automatically install all exporting options, all data access drivers, and several developer components are also excluded. The Custom installation option will allow you to pick and choose the components you would like to install. It will also indicate the amount of disk space required to install the feature selected. Crystal Reports installation also follows Microsoft’s approach to installation on demand. This means that some of the features will not be installed until you have attempted to utilize the feature. There will be a momentary waiting period while the feature installs. Some features may require the installation CD to be installed. Due to registry changes and system file updates, administrator privileges are required to install the application onto Windows NT, 2000, XP and Vista computers.

Minimum Installation Requirements
Crystal Reports has been tested and approved to be used on the following operating systems. Windows Vista Windows 2003 Server Windows XP Professional SP2 Crystal Reports requires a 450 MHz or higher Pentium compatible CPU. A minimum memory requirement to install the application is 128 MB. It is recommended that the system has 256 MB for a trouble-free installation. 4G Maximum. Crystal Reports requires 1 GB of free disk space to properly install. 1.5 GB recommended

208

Crystal Reports 2008 Designer 2 Workshop Appendix C: Installation and System Requirements

©2008 Vision Harvest, Inc.

NOTES

209

Crystal Reports 2008 Designer 2 Workshop Appendix C: Installation and System Requirements

©2008 Vision Harvest, Inc.

NOTES

210

Crystal Reports 2008 Designer 2 Workshop Appendix D: Setup Instructions for Crystal Reports 2008

©2008 Vision Harvest, Inc.

Appendix D Setup Instructions for Crystal Reports 2008

211

Crystal Reports 2008 Designer 2 Workshop Appendix D: Setup Instructions for Crystal Reports 2008

©2008 Vision Harvest, Inc.

Crystal Reports 2008 Application installation Instructions
1. 2. Run Setup.exe from an installation CD or from the root directory of the extracted folder is product was downloaded Choose English and then click OK

3.

Click Next in the Setup Welcome Dialog

4.

Accept the License Agreement and then click Next

212

Crystal Reports 2008 Designer 2 Workshop Appendix D: Setup Instructions for Crystal Reports 2008
5.

©2008 Vision Harvest, Inc.

Enter Name, Organization Name and valid Product Keycode and then click Next

6.

Choose a Typical installation, leave the Destination folder set to default and click Next

213

Crystal Reports 2008 Designer 2 Workshop Appendix D: Setup Instructions for Crystal Reports 2008
7.

©2008 Vision Harvest, Inc.

Ensure the English language pack is selected. No other language packs are required. Click Next

8.

Once the Start Installation dialog appears, click Next

214

Crystal Reports 2008 Designer 2 Workshop Appendix D: Setup Instructions for Crystal Reports 2008
9. 10. The installation begins and can last up to 15 minutes

©2008 Vision Harvest, Inc.

When the installation is complete the Successfully Installed dialog appears. Leave the Check for product updates option checked on and click Finish

11.

The installation program searches for available updates. Proceed to update if necessary or click Finish

Installing Required Class Files
1. Download class files from: http://www.visionharvest.com/Downloads/CR2008D2ClassFiles.zip

2.

Unzip or uncompress the downloaded file into you “My Documents” directory or “Documents” directory if using Windows Vista

215

Crystal Reports 2008 Designer 2 Workshop Appendix D: Setup Instructions for Crystal Reports 2008

©2008 Vision Harvest, Inc.

NOTES

216

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements

©2008 Vision Harvest, Inc.

Appendix E Function and Operator Locations

217

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements

©2008 Vision Harvest, Inc.

Following is a list of Functions available in the middle list in the Formula Editor: Major Categories are listed in bold Minor Categories are listed in italics Function names are listed in regular text Math Abs(x) Sgn(x) Int(x) Round Round(x) Round(x, #places) RoundUp RoundUp(x) RoundUp(x, # places) Truncate Truncate (x) Truncate (x, #places) MRound MRound(x) MRound(x, multiple) Ceiling Ceiling(x) Ceiling(x, multiple) Floor Floor(x) Floor(x, multiple) Remainder(num, denom) Sin(x) Cos(x) Tan(x) Atn(x) Pi Sqr(x) Exp(x) Log(x) Rnd Rnd Rnd(seed) Summary Sum Sum(fld) Sum(fld, condFld) Sum(fld, condFld, cond) Average Average(fld) Average(fld, condFld) Average(fld, condFld, cond) Summary (continued) StdDev StdDev(fld) StdDev(fld, condFld) StdDev(fld, condFld, cond) PopulationStdDev PopulationStdDev(fld) PopulationStdDev(fld, condFld) PopulationStdDev(fld, condFld, cond) Variance Variance(fld) Variance(fld, condFld) Variance(fld, condFld, cond) PopulationVariance PopulationVariance(fld) PopulationVariance(fld, condFld) PopulationVariance(fld, condFld, cond) Maximum Maximum(fld) Maximum(fld, condFld) Maximum(fld, condFld, cond) Minimum Minimum(fld) Minimum(fld, condFld) Minimum(fld, condFld, cond) Count Count(fld) Count(fld, condFld) Count(fld, condFld, cond) DistinctCount DistinctCount(fld) DistinctCount(fld, condFld) DistinctCount(fld, condFld, cond) Correlation Correlation(fld) Correlation(fld, condFld) Correlation(fld, condFld, cond) Covariance Covariance(fld) Covariance(fld, condFld) Covariance(fld, condFld, cond) WeightedAverage WeightedAverage(fld) WeightedAverage(fld, condFld) WeightedAverage(fld, condFld, cond)
218

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements
Summary (continued) Median Median(fld) Median(fld, condFld) Median(fld, condFld, cond) PthPercentile PthPercentile(fld) PthPercentile(fld, condFld) PthPercentile(fld, condFld, cond) NthLargest NthLargest(fld) NthLargest(fld, condFld) NthLargest(fld, condFld, cond) NthSmallest NthSmallest(fld) NthSmallest(fld, condFld) NthSmallest(fld, condFld, cond) Mode Mode(fld) Mode(fld, condFld) Mode(fld, condFld, cond) NthMostFrequent NthMostFrequent(fld) NthMostFrequent(fld, condFld) NthMostFrequent(fld, condFld, cond) PercentOfSum PercentOfSum(fld, condFld) PercentOfSum(fld, condFld, cond) PercentOfSum(fld, innerCondFld, outerCondFld) PercentOfSum(fld, innerCondFld, innerCond, outerCondFld) PercentOfSum(fld, innerCondFld, outerCondFld, outerCond) PercentOfSum(fld, innerCondFld, innerCond, outerCondFld, outerCond) PercentOfAverage PercentOfAverage(fld, condFld) PercentOfAverage(fld, condFld, cond) PercentOfAverage(fld, innerCondFld, outerCondFld) PercentOfAverage(fld, innerCondFld, innerCond, outerCondFld) PercentOfAverage(fld, innerCondFld, outerCondFld, outerCond) PercentOfAverage(fld, innerCondFld, innerCond, outerCondFld, outerCond)

©2008 Vision Harvest, Inc.

Summary (continued) PercentOfMaximum PercentOfMaximum(fld, condFld) PercentOfMaximum(fld, condFld, cond) PercentOfMaximum(fld, innerCondFld, outerCondFld) PercentOfMaximum(fld, innerCondFld, innerCond, outerCondFld) PercentOfMaximum(fld, innerCondFld, outerCondFld, outerCond) PercentOfMaximum(fld, innerCondFld, innerCond, outerCondFld, outerCond) PercentOfMinimun PercentOfMinimum(fld, condFld) PercentOfMinimum(fld, condFld, cond) PercentOfMinimum(fld, innerCondFld, outerCondFld) PercentOfMinimum(fld, innerCondFld, innerCond, outerCondFld) PercentOfMinimum(fld, innerCondFld, outerCondFld, outerCond) PercentOfMinimum(fld, innerCondFld, innerCond, outerCondFld, outerCond) PercentOfCount PercentOfCount(fld, condFld) PercentOfCount(fld, condFld, cond) PercentOfCount(fld, innerCondFld, outerCondFld) PercentOfCount(fld, innerCondFld, | innerCond, outerCondFld) PercentOfCount(fld, innerCondFld, outerCondFld, outerCond) PercentOfCount(fld, innerCondFld, innerCond, outerCondFld, outerCond) PercentOfDistinctCount PercentOfDistinctCount(fld, condFld) PercentOfDistinctCount(fld, condFld, cond) PercentOfDistinctCount(fld, innerCondFld, outerCondFld) PercentOfDistinctCount(fld, innerCondFld, innerCond, outerCondFld) PercentOfDistinctCount(fld, innerCondFld, outerCondFld, outerCond) PercentOfDistinctCount(fld, innerCondFld, innerCond, outerCondFld, outerCond)

219

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements
Summary (continued) BooleanConditions On any change On change to yes On change to no On every yes On every no On next is yes On next is no Date Conditions For each day For each week For each two weeks For each half month For each month For each quarter For each half year For each year Time Conditions For each second For each minute For each hour For each AM/PM Financial ACCRINT ACCRINT(issue,firstInterest,settlement, rate,parValue,frequency) ACCRINT(issue,firstInterest,settlement, rate,parValue,frequency,basis) ACCRINTM ACCRINTM(issue,maturity,rate,parValue, basis) ACCRINTM(issue,maturity,rate,parValue, basis) AmorDEGRC AmorDEGRC(cost,purchaseDate, firstPeriod,salvage,period,rate) AmorDEGRC(cost,purchaseDate, firstPeriod,salvage,period,rate,basis) AmorLINC AmorLINC(cost,purchaseDate, firstPeriod,salvage,period,rate) AmorLINC(cost,purchaseDate, firstPeriod,salvage,period,rate,basis) CoupDayBS CoupDaysBS(settlement,maturity, frequency) CoupDaysBS(settlement,maturity, frequency,basis)

©2008 Vision Harvest, Inc.

Financial (continued) CoupDays CoupDays(settlement,maturity, frequency) CoupDays(settlement,maturity, frequency,basis) CoupDaysNC CoupDaysNC(settlement,maturity, frequency) CoupDaysNC(settlement,maturity, frequency,basis) CoupNCD(settlement,maturity,frequency) CoupNum(settlement,maturity,frequency) CoupPCD(settlement,maturity,frequency) CumIPMT(rate,nPeriods,presentValue,start, ` end,type) CumPRINC(rate,nPeriods,presentValue,start, end,type) DB DB(cost,salvage,life,period) DB(cost,salvage,life,period,month) DDB DDB(cost, salvage, life, period) DDB(cost, salvage, life, period, factor) Days360 Days360(start,end) Days360(start,end,method) DISC DISC(settlement,maturity,price, redemption) DISC(settlement,maturity,price, redemption,basis) DollarDE(fraction,base) DollarFR(decimal,base) Duration Duration(settlement,maturity,rate,yield, frequency) Duration(settlement,maturity,rate,yield, frequency,basis) Effect(rate,periods) FV FV(rate, nPeriods, payment) FV(rate, nPeriods, payment, presentValue) FV(rate, nPeriods, payment, presentValue, type) FVSchedule(value,rates)

220

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements
Financial (continued) IntRate IntRate(settlement,maturity,purchase, redemption) IntRate(settlement,maturity,purchase, redemption,basis) IPmt IPmt(rate, period, nPeriods, presentValue) IPmt(rate, period, nPeriods, presentValue, futureValue) IPmt(rate, period, nPeriods, presentValue, futureValue, type) IRR IRR(values) IRR(values, guess) ISPMT(rate,period,nPeriods,value) MDuration MDuration(settlement,maturity,rate, yield,frequency) MDuration(settlement,maturity,rate, yield,frequency,basis) MIRR(values, financeRate, reinvestRate) Nominal(rate,periods) NPer NPer(rate, payment, presentValue) NPer(rate, payment, presentValue, futureValue) NPer(rate, payment, presentValue, futureValue, type) NPV(rate, values) OddFPrice OddFPrice(settlement,maturity,issue, first,rate,yield,value,frequency) OddFPrice(settlement,maturity,issue, first,rate,yield,value,frequency,basis) OddFYield OddFYield(settlement,maturity,issue, first,rate,purchase,redemption, frequency) OddFYield(settlement,maturity,issue, first,rate,purchase,redemption, frequency,basis) OddLPrice OddLPrice(settlement,maturity,last,rate, purchase,redmption,frequency) OddLPrice(settlement,maturity,last,rate, purchase,redmption,frequency,basis)

©2008 Vision Harvest, Inc.

Financial (continued) OddLYield OddLYield(settlement,maturity,last,rate, purchase,redemption,frequency) OddLYield(settlement,maturity,last,rate, purchase,redemption,frequency,basis) Pmt Pmt(rate, nPeriods, presentValue) Pmt(rate, nPeriods, presentValue, futureValue) Pmt(rate, nPeriods, presentValue, futureValue, type) PPmt PPmt(rate, period, nPeriods, presentValue) PPmt(rate, period, nPeriods, presentValue, futureValue) PPmt(rate, period, nPeriods, presentValue, futureValue, type) Price Price(settlement,maturity,rate,yield, value,frequency) Price(settlement,maturity,rate,yield, value,frequency,basis) PriceDisc PriceDisc(settlement,maturity,rate, value) PriceDisc(settlement,maturity,rate, value,basis) PriceMat PriceMat(settlement,maturity,issue,rate, yield) PriceMat(settlement,maturity,issue,rate, yield,basis) PV PV(rate, nPeriods, payment) PV(rate, nPeriods, payment, futureValue) PV(rate, nPeriods, payment, futureValue, type) Rate Rate(nPeriods, payment, presentValue) Rate(nPeriods, payment, presentValue, futureValue) Rate(nPeriods, payment, presentValue, futureValue, type) Rate(nPeriods, payment, presentValue, futureValue, type, guess)

221

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements
Financial (continued) Received Received(settlement,maturity,value, rate) Received(settlement,maturity,value, rate,basis) SLN(cost, salvage, life) SYD(cost, salvage, life, period) TBillEq(settlement,maturity,rate) TBillPrice(settlement,maturity,rate) TBillYield(settlement,maturity,rate) VDB VDB(cost,salvage,lifetime,start,end) VDB(cost,salvage,lifetime,start,end, factor) VDB(cost,salvage,lifetime,start,end, noSwitch) VDB(cost,salvage,lifetime,start,end, factor,noSwitch) XIRR XIRR(values,dates) XIRR(values,dates) XNPV(rate,values,dates) YearFrac YearFrac(start,end) YearFrac(start,end,basis) Yield Yield(settlement,maturity,rate,purchase, redemption,frequency) Yield(settlement,maturity,rate,purchase, redemption,frequency,basis) YieldDisc YieldDisc(settlement,maturity,purchase, redemption) YieldDisc(settlement,maturity,purchase, redemption,basis) YieldMat YieldMat(settlement,maturity,issue,rate, price) YieldMat(settlement,maturity,issue,rate, price,basis) Strings Length(str) Trim(str) TrimLeft(str) TrimRight(str) UpperCase(str) LowerCase(str) ProperCase(str)

©2008 Vision Harvest, Inc.

Strings (continued) StrReverse(str) NumericText(str) ToNumber(x) ToText ToText (x) ToText (x, y) ToText (x, y, z) ToText (x, y, z, w) ToText (x, y, z, w, q) ToWords ToWords(x) ToWords(x, #places) ToWords(x, #places, formtype) ReplicateString(str, #copies) Space(x) InStr InStr(str1, str2) InStr(start, str1, str2) InStr(str1, str2, compare) InStr(start, str1, str2, compare) InStrRev InStrRev(inputString, findString) InStrRev(inputString, findString, startPosition) InStrRev(inputString, findString, startPosition, compare) StrCmp StrCmp(str1, str2) StrCmp(str1, str2, compare) Mid Mid(str, start) Mid(str, start, length) Left(str, length) Right(str, length) Val(str) ChrW(x) AscW(str) Filter Filter(inputStrings, searchString) Filter(inputStrings, searchString, include) Filter(inputStrings, searchString, include, compare)

222

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements
Strings (continued) Replace Replace(inputString, findString, replaceString) Replace(inputString, findString, replaceString, startPosition) Replace(inputString, findString, replaceString, startPosition, count) Replace(inputString, findString, replaceString, startPosition, count, compare) Join Join(list) Join(list, delimiter) Split Split(inputString) Split(inputString, delimiter) Split(inputString, delimiter, count) Split(inputString, delimiter, count, compare) Roman Roman(value) Roman(value,form) URLEncode URLEncode(inputString) URLEncode(inputString, encodingScheme) URLEncode(inputString, encodingScheme,neverEncode) URLEncode(inputString, encodingScheme,neverEncode, alwaysEncode) URLEncode(inputString, encodingScheme,characterSet) URLEncode(inputString, encodingScheme,characterSet, neverEncode) URLEncode(inputString, encodingScheme,characterSet, neverEncode,alwaysEncode) URLDecode URLDecode(inputString) URLDecode(inputString, encodingScheme) URLDecode(inputString, encodingScheme,characterSet) Date/Time CurrentDate CurrentTime CurrentDateTime

©2008 Vision Harvest, Inc.

Date/Time (continued) Date Date(dateTime) Date(YYYY, MM, DD) Time Time(dateTime) Time(HH, MM, SS) DateTime DateTime(date, time) DateTime(YYYY, MM, DD) DateTime(YYYY, MM, DD, HH, MM, SS) DateValue DateValue(number or string) DateValue(dateTime) DateValue(YYYY, MM, DD) TimeValue TimeValue(number or string) TimeValue(dateTime) TimeValue(HH, MM, SS) DateTimeValue DateTimeValue(number or string) DateTimeValue(date, time) DateTimeValue(date) DateTimeValue(YYYY, MM, DD) DateTimeValue(YYYY,MM,DD,HH, MM,SS) DateSerial(year, month, day) TimeSerial(hour, minute, second) IsDate(string or number) IsTime(string or number) IsDateTime(string or number) Year(x) Month(x) Day(x) DayOfWeek DayOfWeek(date) DayOfWeek(date, firstDayOfWeek) Hour(x) Minute(x) Second(x) MonthName MonthName(month) MonthName(month, abbreviate) WeekdayName WeekdayName(weekday) WeekdayName(weekday, abbreviate) WeekdayName(weekday, abbreviate, firstDayOfWeek) Timer

223

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements
Date/Time (continued) DateAdd(intervalType, nIntervals, startDateTime) DateDiff DateDiff(intervalType, startDateTime, endDateTime) DateDiff(intervalType, startDateTime, endDateTime, firstDayOfWeek) DatePart DatePart(intervalType, inputDateTime) DatePart(intervalType, inputDateTime, firstDayOfWeek,) DatePart(intervalType, inputDateTime, firstDayOfWeek, firstWeekOfYear) First Day of Week Constants UseSystem Sunday Monday Tuesday Wednesday Thursday Friday Saturday First Week of Year Constants UseSystem FirstJan1 FirstFourDays FirstFullWeek ShiftDateTime(inputDateTime, inputTimeZone,outputTimeZone) Date Ranges WeekToDateFromSun MonthToDate YearToDate Last7Days Last4WeeksToSun LastFullWeek LastFullMonth AllDatesToToday AllDatesToYesterday AllDatesFromToday AllDatesFromTomorrow Aged0To30Days Aged31To60Days Aged61To90Days Over90Days Next30Days Next31To60Days Next61To90Days

©2008 Vision Harvest, Inc.

Date Ranges (continued) Next 91To365Days Calendar1stQtr Calendar2ndQtr Calendar3rdQtr Calendar4thQtr Calendar1stHalf Calendar2ndHalf LastYearMTD LastYearYTD Arrays MakeArray(x, …) UBound(array) Sum(x) Average(x) StdDev(x) PopulationStdDev(x) Variance(x) PopulationVariance(x) Maximum(x) Minimum(x) Count(x) DistinctCount(x) Ranges HasLowerBound(x) HasUpperBound(x) IncludesLowerBound(x) IncludesUpperBound(x) Type Conversion CBool(number or currency) CCur(number, currency or string) CDbl(number, currency,string or boolean) CStr CStr(x) CStr(x, y) CStr(x, y, z) CStr(x, y, z, w) CStr(x, y, z, w, q) CDate CDate(number or string) CDate(dateTime) CDate(YYYY, MM, DD) CTime CTime(number or string) CTime(dateTime) CTime(HH, MM, SS)

224

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements
Type Conversion (continued) CDateTime CDateTime(number or string) CDateTime(date, time) CdateTime(date) CDateTime(YYYY, MM, DD) CDateTime(YYYY, MM, DD, HH, MM, SS) Programming Shortcuts Choose(index, choice1, …) IIF(expression, truePart, falsePart) Switch(expr1, value1, expr2, value2, …) Evaluation Time BeforeReadingRecords WhileReadingRecords WhilePrintingRecords EvaluateAfter(x) Print State CountHierarchicalChildren (groupLevel) CurrentPageOrientation HasValue (param-fld) Previous(fld) Next(fld) IsNull(fld) PreviousIsNull(fld) NextIsNull(fld) PageNumber TotalPageCount PageNofM RecordNumber GroupNumber RecordSelection GroupSelection InRepeatedGroupHeader OnFirstRecord OnLastRecord DrillDownGroupLevel HierarchyLevel(groupingLevel) Document Properties PrintDate PrintTime PrintTimeZone ModificationDate ModificationTime DataDate DataTime DataTimeZone ReportTitle

©2008 Vision Harvest, Inc.

Print State (continued) ReportComments Filename FileAuthor FileCreationDate CurrentCEUserName CurrentCEUserID GroupingLevel (fld) CurrentCEUserTimeZone ContentLocale Alerts IsAlertEnabled(alertName) IsAlertTriggered(alertName) AlertMessage(alertName) Additional Functions 2000 (u212000.dll) DateTo2000(Date,Number) DTSTo2000(DateTimeString,Number) dts (u2ldts.dll) DTSToDate(DateTimeString) DTSToTimeString(DateTimeString) DTSToSeconds(DateTimeString) exch (u2lexch.dll) ExchGetID(address) ExchGetOrganization(address) ExchGetSite(address) ExtractString(orig, startStr, endStr) EventNumber(eventNum) ExchGetPath(Path) ByteToText(byte) finra (u2lfinra.dll) FRCurrentRatio(CurrentAssets, CurrentLiabilities) FRQuickRation(CurrentAssets, Inventories, CurrentLiabilities) FRDebtEquityRatio(TotalLiabilities, TotalEquity) FREquityVsTotalAssets(TotalEquity, TotalAssets) FRNetProfitMargin(NetProfit, Sales) FRGrossProfitMargin(GrossProfit, Sales) FROperatingProfitMargin( OperatingProfit, Sales) FRInterestCoverage(CashFlow, InterestExpenses) FRCashFlowVsTotalDebt(CashFlow, TotalDebt)

225

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements
Additional Functions (continued) FRReturnOnEquity(NetProfit, TotalEquity) FRReturnOnNetFixedAssets(NetProfit, NetFixedAssets) FRReturnOnTotalAssets(NetProfit, TotalAssets) FRReturnOnInvestedCapital(NetProfit, TotalBankDebts, TotalEquity) FRReturnOnCommonEquity(NetProfit, PreferredDividend, CommonEquity) FREarningsPerCommonShare( NetProfit, PreferredDividend, NumOfCommonShare) FRAccRecTurnover( AccountReceivable, Sales, NumOfDays) FRInventoryTurnover(Inventory, Sales, NumofDays) FRPriceEarningsRatio(MarketPrice, EarningsPerShare) FRDividendYield(Dividend, MarketPrice) samp1 (u2lsamp1.dll) Now Picture(string, picture) LooksLike(string, mask) Soundex(string) 2000 (u25200.dll) DateTimeTo2000(DateTime, Number) dts (u25dts.dll) DTSToDateTime(DateTimeString) DTSToTimeField(DateTimeString) DateTimeToDate(dateTime) DateTimeToTime(dateTime) DateTimeToSeconds(dateTime) azalea (u2I2000.dll) Several Barcoding functions

©2008 Vision Harvest, Inc.

226

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements

©2008 Vision Harvest, Inc.

Following is a list of Operators available in the right list in the Formula Editor: Major Categories are listed in bold Function names are listed in regular text Arithmetic Add (x + y) Subtract (x – y) Multiply (x * y ) Divide ( x / y) Integer divide (x \ y) Percent ( x % y ) Modulus ( x mod y) Negate (-x) Exponentiate (x ^ y) Conversion To currency ($x) Comparisons Equal (x = y) Not equal (x <> y) Less than (x < y) Greater than (x > y) Less or equal (x <= y) Greater of equal ( x>=y) Strings Concatenate (x + y) Concatenate (x & y) Subscript (x [y]) In string (x in y) Insert Empty String (“”) Ranges In range (x in y) Make range (x to y) Left endpoint excluded range (x_to y) Right endpoint excluded range (x to_y) Both endpoints excluded range (x_to_y) Up to (upTo x) Up to but not including(upTo_x) Up from (upFrom x) Up from but not including(upFrom_x) Boolean Not (not x) And (x and y) Or (x or y) Xor (x xor y) Eqv (x eqv y) Imp ( x imp y) Arrays Make array ([x, …]) Subscript (x [y]) In array (x in y) redim x [n] redim preserve x [n] Pattern Starts with (x startsWith y) Like pattern (x like y) Control Structures if x then y else z select x case a: y default: z for i := a to b step c do z exit for while x do y do x while y exit while option loop maxIterations Other Parentheses ( (x) ) Assignment (x := y) Comment (//) Date-time literal (#…#) Scope Local Global Shared

227

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements
Variable Declarations BooleanVar x := y; NumberVar x := y; CurrencyVar x := y; DateVar x := y; TimeVar x := y; DateTimeVar x := y; StringVar x := y; NumberVar range x := y to z; CurrencyVar range x := y to z; DateVar range x := y to z; TimeVar range x := y to z; DateTimeVar range x := y to z; StringVar range x := y to z; BooleanVar array x := [y, z, …]; NumberVar array x := [y, z, …]; CurrencyVar array x := [y, z, …]; DateVar array x := [y, z, …]; TimeVar array x := [y, z, …]; DateTimeVar array x := [y, z, …]; StringVar array x := [y, z, …]; NumberVar range array x := [a to c, y to z, …]; CurrencyVar range array x := [a to c, y to z, …]; DateVar range array x := [a to c, y to z, …]; TimeVar range array x := [a to c, y to z, …]; DateTimeVar range array x := [a to c, y to z, …]; StringVar range array x := [a to c, y to z, …];

©2008 Vision Harvest, Inc.

228

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements

©2008 Vision Harvest, Inc.

NOTES

229

Crystal Reports 2008 Designer 2 Workshop Appendix E: Installation and System Requirements

©2008 Vision Harvest, Inc.

NOTES

230

Crystal Reports 2008 Designer 2 Workshop Appendix F: Glossary

©2008 Vision Harvest, Inc.

Appendix F Glossary

231

Crystal Reports 2008 Designer 2 Workshop Appendix F: Glossary

©2008 Vision Harvest, Inc.

Absolute Formatting Active Database Active Server Pages

Add-ins Aggregate Function Add Column Add Row Alias Another report Any Value Background Color Between

Boolean expression Browser Case Sensitive Check Boxes Columns Column Concatenate Condition

Conditional Formatting Constant

Glossary The data field formatting option that can only be turned on or off based on the presence or absence of an attribute. See also, Conditional Formatting An active database is a database that has been selected for use in a report ASPs are web pages that run under Microsoft’s Internet Information Server (IIS) version 3.0 and later. They are dynamic web pages that can be viewed from many common web browsers. You can use Crystal’s Automation Server, the ActiveX Controls, and Active Data Driver to create active web sites that display reports from an Internet or intranet site Crystal Reports Add-ins let you create a report directly from Microsoft Excel or Microsoft Access An operation that summarizes data. This is often used with an SQL query to combine records and summarize a field or fields A data field is inserted into the Column section when first clicking on the field and then clicking this option A field is inserted into the row section when first clicking on the field and then clicking this option Aliases are pointers that tell the program where it should look for a database field. You can use alias names on tables in Crystal and on table and fields in Crystal Dictionaries An option in the Report Gallery box that allows the user to open existing reports An option in the Select Expert box. If you leave “any value” in the box, you’ve chosen not to apply any conditions to the data We can define a background color for each section. The background fill is not adjustable and always adjusts itself to the width of the page and the defined height of the section An option in the Select Expert box. Choose records that fall between certain values; perhaps call center agent “talk time” that falls between 2 minutes and 6 minutes or hourly wages between $4.75 and $10.00 A Boolean expression is an expression that defines a logical relationship between two or more items. This type of expression always results in a TRUE or FALSE answer A Browser is an application that enables viewing of documents in HTML format Crystal formulas are not case specific. Caps and lower case are considered the same Boxes found in many formatting and editing options that allow the user to turn a feature “On” or “Off ” Columns are fields that will display as a group across the Cross-Tab A column is the display of data from a single field or formula. Columns run down the page To concatenate is to join two or more text strings together to form a single continuous string. The concatenate operator is the plus sign + In an If…then…else statement the condition is the If part of the formula. It is a test to be performed. The results of the test determine whether Crystal performs the Then tasks or the Else tasks Conditional formatting is formatting that applies on if certain situations occur. For example, you might format a number field to display in red if the number is negative A value that is fixed and unchanging in a formula

Control Sort

An object used to allow a user to control the sort order on a group or field

232

Crystal Reports 2008 Designer 2 Workshop Appendix F: Glossary
Glossary Cross-Tabs Control Structures

©2008 Vision Harvest, Inc.

Current Date Database Data Source Data Date Data File

Data Time Debug Details Section Dictionary

Dynamic Link Library Equal Join Evaluation time

Export

Fields

Flat Formula For loop Formatting Toolbar Formatting Formula

A report type option that produces Cross-Tab reports to show relationships between different data fields Control structures control the flow of logic in a formula. You use them to build formula conditions that, if met, trigger specific consequences or repeat a sequence of actions under certain conditions. Control structures are if…then…else, for loops, while loops, and select expressions This function will produce a date based on your computer system’s date Any of a variety of information gathering tools. The tables used in Crystal Reports are contained within databases A particular set of tables, queries, dictionaries or stored procedures that provide data for a report Prints the date that the data in the report was last refreshed Found in the Report Gallery after selecting Custom reports. This connection is used for PC based databases run from the C: drive or from a server. Examples include MS-Access, Paradox, Btrieve, Dbase and FoxPro Prints the time that the data in the report was last refreshed Eliminates errors that occur when you run a formula The Details section of a report contains a row for each record returned from the database Found in the Report Gallery. Used to create reports from a Crystal Dictionary or from a Crystal Query. Dictionaries act as a micro-view of the database. They allow tables and fields to have meaningful names A Dynamic Link Library (DLL) is a file that contains Windows functions. DLLS are used by developers to extend the capabilities of Windows applications Refers to linking tables within the Visual Linking Expert. An Equal Join requires that to join a record from the left table, there must be an equal match in the right table Evaluation time refers to the stage in the reporting process when a formula is evaluated. The three evaluations time functions are: BeforeReadingRecords, WhileReadingRecords and WhilePrintingRecords To export is to distribute the report to a disk file or through e-mail to a different format. Crystal allows you export to a number of spreadsheet, word processing, database and HTML formats Fields are accumulations of data about a particular subject stored within a table in a database. Fields are selected from tables and placed on the report in a variety of ways, the most basic being, from the Field Explorer box early in the development of your report. In the formula creation process, Fields are always shown within “curly braces” A formula that does not reference any database field For/Next loops enable you to evaluate a sequence of statements multiple times. for i := a to b do c Available for use in both the Design and Preview windows. You can choose to display it or hide it. Used to quickly format an object. A fast way to format both text and numbers Allows the user to change the appearance of the report based on a wide variety of criteria A formula is a statement that performs some calculation or modification to data from the database or constant value

233

Crystal Reports 2008 Designer 2 Workshop Appendix F: Glossary

©2008 Vision Harvest, Inc.

Formula Editor Free-Form Placement Functions

Glossary The dialog box used to create and edit formulas. It contains tools for inserting fields, functions and operators into a formula, for checking formula syntax, for typing formulas An option that allows you to place fields freely on your report rather than forcing fields to be placed at fixed points A built-in procedure or subroutine used to evaluate, calculate or transform data.. Us functions as a kind of short hand for complex operations. The syntax for functions is as follows: FunctionName (argument, argument, argument)

A grand total is the summary of all values in a column, for the entire report An option in the Select Expert box. Using this choice selects only values greater than the criteria you set Grid The grid is an underlying network of points that you can use to help you line up objects on a report Group A group is a set of records that are related to each other in some way. You specify a field on which to group and Crystal Reports puts all records with the same value in that group Group Header and The Group Header and Footer are sections that appear at the beginning and end of each Footer group in the report Guidelines Non-printing lines that you can use to align, move and resize objects in the report Hierarchical Grouping Enables you to group data in a report to show hierarchical relationships. When you group data hierarchically, you sort information based on the relationship between two fields Highlighting Expert The Highlighting Expert is used to change the font, border or background attributes of an object under certain conditions Hyperlink An interactive link to a web site, another file, an e-mail address, the current field value, or another Crystal Report file Index An index is a file that identifies the location of each record in a database. Since this is a small file and can be searched or sorted quickly, an index file makes locating fields a quicker process. Just like using an index in a manual makes locating a specific topic quicker If Then Else If …Then...Else… Formulas describe conditions that control the display of data. In common language it might look like this…If the Last Year’s Sales figure is less than $50000 Then make the value bold and italicized, Else (otherwise) make no changes. These formulas are particularly helpful to bring attention to significantly higher or lower performance or to risk factors associated with specific values InStr This function allows us to find the position of a particular character. For example InStr (“abc-def”,”-”) would test the string to find the position for the “-” character and would return the number 4. This is a great tool for extracting a group of characters from a field when the starting or ending position is variable from field to field Keep Together This option refers to keeping a section together in relation to page breaks. If there isn’t enough page left to print the section, then rather than having the page break occur in the middle of the section, the entire section is carried over to the next page Last Modification Date Shows the date when the report was last modified (new tables added, etc.) based on the PC’s calendar/clock Last Modification Time Shows the time when the report was last modified based on the PC’s clock

Grand Total Greater than

234

Crystal Reports 2008 Designer 2 Workshop Appendix F: Glossary

©2008 Vision Harvest, Inc.

Less than

Like

Linking Map Expert Mid

Multi-column Nesting Null Object Frame

One of

One-to-Many Relationship Operators

Order of precedence

Outer Join

Page Header and Footer Parameter field

Glossary An option within the Select Expert box. Perhaps you want to see all sales less than $50,000. Choosing this option will display all values of $49,999.99 and less (including negative DOS characters like ‘?’ or ‘*’ can be used with this option to select records with similar, but not identical values. You may enter ‘is like D*’ to display records that include Denver, Dallas, Des Moines or Dusseldorf A method of bringing two or more databases together within a single report and joining tables of data with at least one matching field The Map Expert is a powerful tool for organizing your data by placing geographic maps on a report. You can drill down on these maps to see underlying data Applies to formula creation. This function works much the same way as Subscript [], and is a common function in other programming type application. It allows us to specify which character position we want to extract from a field value An option in the Report Gallery as you prepare to develop a new report. Useful for creating mailing labels or other multi-column text documents Nesting means to use one If… Then… Else statement inside another Null means there is no data in that cell in the database. NOTE: it does NOT mean that the value is zero An object frame is a rectangular cursor that appears as an aid to placing database fields and formulas on your report. When you move the object frame to a location on the report, then click the mouse button, Crystal Reports places the object in the location you specified. This can also be used to refer to the rectangular box that indicates the location of an on-demand subreport in a report Found in the Select Expert box. If you want to see several specific values (but not others) you can choose “one of” and then enter just those values you want to see such as 5000, 7000, 10,000. The “is not” button can be used here as well One-to-many refers to a situation occurring in linked database tables in which one record in a table can be matched to many records in another table Special symbols that describe an operation or an action to take place between two or more values. Operators are + - * and / <> = etc. Syntax rules allow you to place a space before and after and operator or omit spaces Order of precedence The order of precedence is a set of rules that determines the order in which arithmetic operations take place in a formula. Multiplication and division occur before addition and subtraction Applies to joining tables. There are Left Outer Joins and Right Outer Joins. A Left Outer Join selects all the records from the left table and any matching ones from the right table. A Right Outer Join selects all the records from the right table and any matching tables from the left These sections define items that will appear at the top and bottom of each page of a report A special kind of field that prompts the user for a value. Use of parameter fields lets you change the options for the report at run time on the fly

Page Orientation
Pick List

Used to specify if a report or a section of the report is landscape or portrait
A list for a user to select a value for a parameter. You can import pick lists from any text file

235

Crystal Reports 2008 Designer 2 Workshop Appendix F: Glossary
Glossary Print Date Print Time Population standard deviation Population variance Range of Values

©2008 Vision Harvest, Inc.

Report Header and Footer Report Gallery Refresh

Takes the date from your PC’s calendar/clock and prints it on the report Takes the time from your PC’s clock and prints it on the report This is a statistical test of how the values in an entire population deviate from the mean or average value for the population This is the square of the population standard deviation This will limit the amount a bar can represent. If the value being graphed exceeds the limit then the bar stops at the limit you chose. This option does not limit items from being represented, but instead limits the amount being graphed Sections that define items to print only one time, at the beginning or end of a report The Report Gallery is a dialog box that appears when you begin a new report. It allows you to define how you are going to create the report A Toolbar option that allows the user to require an update to the report, using the most recent data stored in the database. The button resembles a lightning bolt. There are also certain changes made to the report that automatically generate a “Refresh” of the data Applies to creating formulas. This function allows us to represent integer values with symbols such as an “*” Automatically places any comments you make about the report in the File/ Summary Info window along with other information about the report for future reference Like setting page breaks we can reset the page numbers back to 1 after a section has been printed Rows are fields that will display as a group down a Cross-Tab A row is the display of data from a single record in the database. Rows run horizontally across the page The ruler provides a visual reference for positioning and resizing objects on the report. It provides measurements and shows where guidelines are located. You can view the ruler in either Design or Preview view or both These totals are calculated on a record-by-record basis. They total all records in the report or group and can be formatted to work conditionally Each Section corresponds to a specific part of the final, printed report. You will be inserting data fields, text and pictures into different Sections. The Section names are seen in the Design Screen on the left side of the window. Examples are Report Header, Page Header, Details, Report Footer, Page Footer etc. A dialog box used to apply formats to the sections of the report rather than to individual fields The Select statement is similar to an If statement but allows for multiple choices in a manner that is more clear and less repetitive. select x case a: y default: z A powerful Crystal tool that allows the user to determine how data will be displayed on the report. It is most easily accessed by clicking the button on the Tool Bar Server-side processing is a feature that allows you to set up reports that perform the majority of their processing on the server. These reports push only relevant details to your computer, thus saving time and memory

Replicate String Report Comments Reset Page Number After Rows Row Ruler

Running Totals Sections

Section Expert Select Statement

Select Expert Server-side processing

236

Crystal Reports 2008 Designer 2 Workshop Appendix F: Glossary
Glossary Smart Linking

©2008 Vision Harvest, Inc.

Sort SQL/ODBC

Standard Deviation String Formulas Strings Subreports Subtotals Summary Fields Suppress Switch function

Syntax Text Object Toolbar

Total Top N

Total Page Count ToText

Truncate

A very useful feature of Crystal Reports that automatically links common tables within databases. Users can allow Smart Linking to accomplish links or joins or, decide to make the links “manually” The process of organizing the records of the report in a particular order. You can sort in ascending or descending order on any field in the Details section SQL stands for Structured Query Language; a frequently used programming language used to “speak” to the database. ODBC stands for Open Database Connectivity. This connection is used typically for server-based databases like Oracle, Sybase, Informix, and MSSQL Server. ODBC was developed by Microsoft as a “translator” to overcome the variations in dialects between databases. It allows Crystal to communicate with almost any database Standard deviation is the square root of the variance. This is a statistical test of how various values in a set of values deviate from the mean or average value for the set String Formulas are used to perform functions on fields that cannot be acted upon by mathematical formulas. They are useful for modifying how text is displayed on a report A string is a series of textual characters. The characters may be letters, numbers or special characters A subreport is any report within another report. It has all the characteristics of a report except that it cannot contain another subreport Once you have broken a report down into groups, it is possible to have subtotals displayed at the bottom of each group A field that determines the sum, average, minimum, maximum, or count of values in a group. Summary fields are based on a field in the Details section of the report Found within the Section Expert. Suppress works like hide except that the section is permanently suppressed and drill-down capabilities are not allowed The argument list for Switch consists of pairs of expressions and values. Switch evaluates the expressions from left to right, and returns the value associated with the first expression to evaluate to True A set of rules that specifies the proper way to use functions and operators in a formula A text object is an object in a report that can contain typed text, fields from a database or formula fields A quick way to select functions that can also be found in the Menu Bar. Use these as a shortcut to all the features. When holding your pointer over the boxes In the Toolbar you will see their function. It will also show in the Status Bar A total is a sum of values. Subtotals and grand totals are different types of totals Top N is a function that allows the user to make the report display only the highest or lowest values. It is often used to create a group that displays the top sales figures or the lowest accident rate Calculates and prints the total pages in the report This versatile function can, among other things, convert a date value into a text value. It also allows us to format the value to display any or all portion of the data. See a complete listing of format options in the “To Text” on-line help section This function will “cut off ” decimal values based on the “#places” specified. If you specify 0 places then the number 7.59 would be displayed as 7. Notice that truncating a number doesn’t perform any rounding

237

Crystal Reports 2008 Designer 2 Workshop Appendix F: Glossary

©2008 Vision Harvest, Inc.

Underlay Following Sections Variance View Options

Visual Linking Expert X+2 Boxes

Wizards Wildcard Word Wrap

Glossary Rather than having the section print in a linear order, a section can start printing on the page at the same spot the section below it begins to print. This is a great tool for displaying a group graph next to the group data Variance is the square of the standard deviation. It is a measure of the amount by which all values in a group vary from the mean (average) value in the group These options allow control over how much “space” is allowed for either the Design or the Preview portions of the report. Turning these properties “On” or “Off ” will reduce or increase the space. The user decides which view is most useful for the task A powerful tool to create the desired joins between tables These boxes, seen in the formatting functions, allow the user to set criteria for display of certain selected data. Clicking an “X+2” box accesses a formula editor where the user has the opportunity to set the conditions for the display of the data On the Start Page, choose one of four wizards designed to assist report writers in building reports quickly and efficiently A wildcard is a character that takes the place of any character or characters. The ? wildcard takes the place of a single character. The * wildcard takes the place of multiple characters Word wrap is a property of text boxes by which Crystal Reports moves a word to the next line when it is too long to fit on the current line

238

Crystal Reports 2008 Designer 2 Workshop Appendix F: Glossary

©2008 Vision Harvest, Inc.

NOTES

239

Crystal Reports 2008 Designer 2 Workshop Appendix F: Glossary

©2008 Vision Harvest, Inc.

NOTES

240