Anda di halaman 1dari 94

BusinessObjects Advanced Query Building Techniques Guide

BusinessObjects 6.5 Windows

BusinessObjects Advanced Query Building Techniques Guide

Copyright

Copyright 2004 Business Objects. All rights reserved. If you find any problems with this documentation, please report them to Business Objects in writing at documentation@businessobjects.com.

Trademarks

Business Objects, the Business Objects logo, Crystal Reports, and Crystal Enterprise are trademarks or registered trademarks of Business Objects SA or its affiliated companies in the United States and other countries. All other names mentioned herein may be trademarks of their respective owners. This software and documentation is commercial computer software under Federal Acquisition regulations, and is provided only under the Restricted Rights of the Federal Acquisition Regulations applicable to commercial computer software provided at private expense. The use, duplication, or disclosure by the U.S. Government is subject to restrictions set forth in subdivision (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at 252.2277013. Business Objects owns the following U.S. patents, which may cover products that are offered and sold by Business Objects: 5,555,403, 6,247,008 B1, 6,578,027 B2, 6,490,593 and 6,289,352.

Use restrictions

Patents

BusinessObjects Advanced Query Building Guide

Contents
Contents Examples Preface Maximizing Your Information Resources 3 5 7

Information resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Useful addresses at a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 About this guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Chapter 1 Understanding Calculation Contexts 15

Defining the calculation context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 What is extended syntax? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Extended syntax keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Chapter 2 Subqueries in BusinessObjects 35

Using subqueries in the Query Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Creating subqueries by using complex conditions . . . . . . . . . . . . . . . . . . . . 41 Chapter 3 Working with Prompts 45

Creating meaningful LOVs in prompts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Creating an ALL option in a prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Chapter 4 Building Date-Related Queries 57

A technique for date-related queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Chapter 5 Working with Hierarchies 71

Hierarchies in relational databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Chapter 6 Advanced SQL Generation 83

SQL generation in Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

Contents

BusinessObjects Advanced Query Building Guide

Index

93

Contents

BusinessObjects Advanced Query Building Guide

Examples
Specifying an output context with In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Specifying an input context with In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Using context operators and variables to create an aleter . . . . . . . . . . . . . . 24 Specifying and input and an output context with In . . . . . . . . . . . . . . . . . . . 25 Adding a dimension to the input context with ForEach . . . . . . . . . . . . . . . . 27 Removing a dimension from the input context with ForAll . . . . . . . . . . . . . . 28 Using keywords to avoid incorrect results . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Creating a test report to verify a formula . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Show revenue by country and region where the country revenue > $1,000,000 37 Return country, resort and revenue for those countries/resorts with higher than average revenue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Return all leap years . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 How many Fridays are in each month? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Return all dates in all months that begin with a Thursday . . . . . . . . . . . . . . 62 Return the last day of each month in the year 2000 . . . . . . . . . . . . . . . . . . 62 Show revenue and include only those months that end on a particular day or days in the calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Show revenue and include only those months that begin on a particular day or days in the calculation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Show revenue and include only those months that contain X occurrences of day Y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Return all dates in months that have X public holidays . . . . . . . . . . . . . . . . 68 Creating a formatted hierarchy in BusinessObjects . . . . . . . . . . . . . . . . . . . 75 Adding measures to a hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Adding an alerter to a hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Using a derived table to build a visual hierarchy . . . . . . . . . . . . . . . . . . . . . 89

DRAFT

Examples

BusinessObjects Advanced Query Building Guide

Examples

DRAFT

Maximizing Your Information Resources

preface

BusinessObjects Advanced Query Building Guide

Overview
Information, services, and solutions
The Business Objects business intelligence solution is supported by thousands of pages of documentation, available from the products, on the Internet, on CD, and by extensive online help systems and multimedia. Packed with in-depth technical information, business examples, and advice on troubleshooting and best practices, this comprehensive documentation set provides concrete solutions to your business problems. Business Objects also offers a complete range of support and services to help maximize the return on your business intelligence investment. See in the following sections how Business Objects can help you plan for and successfully meet your specific technical support, education, and consulting requirements.

Maximizing Your Information Resources

BusinessObjects Advanced Query Building Guide

Information resources
Whatever your Business Objects profile, we can help you quickly access the documentation and other information you need.

Where do I start?
Below are a few suggested starting points; there is a summary of useful web addresses on page 12. Documentation Roadmap The Documentation Roadmap references all Business Objects guides and multimedia, and lets you see at a glance what information is available, from where, and in what format. View or download the Business Objects Documentation Roadmap at www.businessobjects.com/services/documentation.htm Documentation from the products You can access electronic documentation at any time from the product you are using. Online help, multimedia, and guides in Adobe PDF format are available from the product Help menus. Documentation on the web The full electronic documentation set is available to customers with a valid maintenance agreement on the Online Customer Support (OCS) website at www.businessobjects.com/services/support.htm Buy printed documentation You can order printed documentation through your local sales office, or from the online Business Objects Documentation Supply Store at www.businessobjects.com/services/documentation.htm Search the Documentation CD Search across the entire documentation set on the Business Objects Documentation CD shipped with our products. This CD brings together the full set of documentation, plus tips, tricks, multimedia tutorials, and demo materials. Order the Documentation CD online, from the Business Objects Documentation Supply Store, or from your local sales office.

Information resources

10

BusinessObjects Advanced Query Building Guide

Multimedia Are you new to Business Objects? Are you upgrading from a previous release or expanding, for example, from our desktop to our web solution? Try one of our multimedia quick tours or Getting Started tutorials. All are available via the Online Customer Support (OCS) website or on the Documentation CD.

How can I get the most recent documentation?


You can get our most up-to-date documentation via the web. Regularly check the sites listed below for the latest documentation, samples, and tips. Tips & Tricks Open to everyone, this is a regularly updated source of creative solutions to any number of business questions. You can even contribute by sending us your own tips. www.businessobjects.com/forms/tipsandtricks_login.asp Product documentation We regularly update and expand our documentation and multimedia offerings. With a valid maintenance agreement, you can get the latest documentation in seven languages on the Online Customer Support (OCS) website. Developer Suite Online Developer Suite Online provides documentation, samples, and tips to those customers with a valid maintenance agreement and a Developer Suite license via the Online Customer Support (OCS) website.

Send us your feedback


Do you have a suggestion on how we can improve our documentation? Is there something you particularly like or have found useful? Drop us a line, and we will do our best to ensure that your suggestion is included in the next release of our documentation: documentation@businessobjects.com
NOTE

If your issue concerns a Business Objects product and not the documentation, please contact our Customer Support experts. For information about Customer Support visit: www.businessobjects.com/services/support.htm

Maximizing Your Information Resources

BusinessObjects Advanced Query Building Guide

11

Services
A global network of Business Objects technology experts provides customer support, education, and consulting to ensure maximum business intelligence benefit to your business.

How we can support you?


Business Objects offers customer support plans to best suit the size and requirements of your deployment. We operate three global customer support centers: Americas: San Jose, California and Atlanta, Georgia Europe: Maidenhead, United Kingdom Asia: Tokyo, Japan and Sydney, Australia Online Customer Support Our Customer Support website is open to all direct customers with a current maintenance agreement, and provides the most up-to-date Business Objects product and technical information. You can log, update, and track cases from this site using the Business Objects Knowledge Base.

Having an issue with the product?


Have you exhausted the troubleshooting resources at your disposal and still not found a solution to a specific issue? For support in deploying Business Objects products, contact Worldwide Customer Support at: www.businessobjects.com/services/support.htm

Looking for the best deployment solution for your company?


Business Objects consultants can accompany you from the initial analysis stage to the delivery of your deployment project. Expertise is available in relational and multidimensional databases, in connectivities, database design tools, customized embedding technology, and more. For more information, contact your local sales office, or contact us at: www. businessobjects.com/services/consulting.htm

Looking for training options?


From traditional classroom learning to targeted e-learning seminars, we can offer a training package to suit your learning needs and preferred learning style. Find more information on the Business Objects Education website: www.businessobjects.com/services/education.htm

Services

12

BusinessObjects Advanced Query Building Guide

Useful addresses at a glance


Address
Business Objects Documentation www.businessobjects.com/services/ documentation.htm

Content
Overview of Business Objects documentation. Links to Online Customer Support, Documentation Supply Store, Documentation Roadmap, Tips & Tricks, Documentation mailbox.

Business Objects Documentation mailbox documentation@businessobjects.com Product documentation www.businessobjects.com/services/ support.htm

Feedback or questions about documentation.

The latest Business Objects product documentation, to download or view online.

Business Objects product information Information about the full range of Business Objects products. www.businessobjects.com Developer Suite Online www.techsupport.businessobjects.com Knowledge Base (KB) www.techsupport.businessobjects.com Available to customers with a valid maintenance agreement and a Developer Suite license via the Online Customer Support (OCS) website. Provides all the documentation, latest samples, kits and tips. Technical articles, documents, case resolutions. Also, use the Knowledge Exchange to learn what challenges other users both customers and employees face and what strategies they find to address complex issues. From the Knowledge Base, click the Knowledge Exchange link. Practical business-focused examples.

Tips & Tricks www.businessobjects.com/forms/ tipsandtricks_login.asp

Maximizing Your Information Resources

BusinessObjects Advanced Query Building Guide

13

Address Online Customer Support www.techsupport.businessobjects.com

Content

Starting point for answering questions, resolving issues. Information about registering with Worldwide Customer Support. The range of Business Objects training options and modules.

www.businessobjects.com/services Business Objects Education Services www.businessobjects.com/services/ education.htm

Business Objects Consulting Services Information on how Business Objects can help maximize your business intelligence investment. www.businessobjects.com/services/ consulting.htm

Useful addresses at a glance

14

BusinessObjects Advanced Query Building Guide

About this guide


This guide describes advanced query-building techniques using BusinessObjects and Designer.

Audience
This guide is intended for advanced users of BusinessObjects who are familiar with relational database concepts and BusinessObjects reporting concepts.

Conventions used in this guide


The conventions used in this guide are described in the table below. Convention Small capitals Indicates The names of all products such as BusinessObjects, WebIntelligence, Supervisor, and Designer. Code, SQL syntax, computer programs. For example: @Select(Country\Country Id). This font is also used for all paths, directories, scripts, commands and files for UNIX. Placed at the end of a line of code, the symbol ( ) indicates that the next line should be entered continuously with no carriage return.

This font

Some code more code

$DIRECTORYPATHNAME The path to a directory in the Business Objects installation/configuration directory structure. For example: $INSTALLDIR refers to the Business Objects installation directory. $LOCDATADIR refers to a subdirectory of the BusinessObjects installation directory called locData.

Maximizing Your Information Resources

Understanding Calculation Contexts

chapter

16

BusinessObejcts Advanced Query Building Techniques Guide

Overview
Extended calculation syntax is one of BusinessObjects most powerful yet least understood features. It provide enormous flexibility when building calculations. Extended syntax allows you to retrieve data at the lowest level of aggregation from your database, then manipulate this data at different levels of aggregation in a report. For example, in the same report you can show sales revenue by quarter and by year. Aggregation at different levels is much more difficult with SQL statements because each statement can contain one GROUP BY clause only. To accomplish at the database level what you can accomplish simply in BusinessObjects with extended syntax often requires extremely complex SQL. This chapter gives a detailed, step-by-step explanation of extended sytax. The topics covered are: defining the calculation context context operators (In, ForEach, ForAll) Extended syntax keywords (Body, Block)

Understanding Calculation Contexts

BusinessObejcts Advanced Query Building Techniques Guide

17

Defining the calculation context


What are calculation contexts?
Calculation contexts give you more control over how a formula or measure is evaluated. To understand them, you need to be familiar with basic report concepts. A report contains two kinds of objects: dimensions, which are types of data about your business that can have measures associated with them (for example: products, years, states), and the measures that you can calculate in relation to dimensions (for example: sales revenue, number of sales). For example, a report could show sales revenue (measure) by year (dimension). The important thing to remember about measures is that they are semantically dynamic. This means that the figures returned by a measure depend on the dimensions with which it is associated; in other words, on the context in which it is placed. BusinessObjects places measures in default contexts depending on where they appear in a report, but you can change these defaults. This is what is meant by defining the calculation context. You can see default contexts by creating a block based on the eFashion universe that contains Year and Sales Revenue objects. In this case the Sales Revenue object returns the revenue by year, because revenue is evaluated in the context of the Year dimension. If you then add the Quarter dimension to the block, the figures in the Sales Revenue column change because the default context is now Year and Quarter.

From this you can see that when you place a measure or formula in a block, the default calculation context that BusinessObjects applies includes all the dimensions in the block.

Defining the calculation context

18

BusinessObejcts Advanced Query Building Techniques Guide

What is extended syntax?


Extended syntax allows you to specify calculation contexts explicitly, which means that you do not need to accept BusinessObjects defaults. To use extended syntax you need to be familiar with three concepts: input and output contexts context operators extended syntax keywords

Input and output contexts


A measure or formulas input and output contexts determine what number the measure or formula returns. You use extended syntax to specify these contexts explicitly in order to give yourself maximum control over formulas. What is an input context? A formulas input context is simply the list of dimensions that the formula takes into account when calculating its result. Look at the example from earlier in this chapter:

In the block in the left, BusinessObjects sums Sales Revenue by year; in the block on the right, it sums Sales Revenue by Year and Quarter. The input context of the left block is (Year); the input context of the right block is (Year,Quarter).

Understanding Calculation Contexts

BusinessObejcts Advanced Query Building Techniques Guide

19

What is an output context? A formulas output context causes it to output a value is if it were placed in the footer of a block break (or, in SQL terms, the COMPUTE BY clause of an SQL query). Look at the following report, which contains a break:

What if you want to show the minimum revenue by year in a column in the block that has no break? In this case, you need to tell BusinessObjects that the formulas output context is (Year). The block looks like this:

What is extended syntax?

20

BusinessObejcts Advanced Query Building Techniques Guide

Expressed in words, you are telling BusinessObjects to sum revenues by year and quarter (the input context), then output the smallest of these values that occurs in each year (the output context). The formula for the Min by Year column is Min(<Sales revenue> In (<Year> ,<Quarter>)) In <Year>.

Extended syntax context operators


You specify a formula context explicitly by including context operators in the formula. There are three context operators: In, ForEach and ForAll. The In context operator You use the In operator to specify an explicitly-named list of dimensions. When specifying an input context, you place In <dimension list> inside the function parentheses. When you specify an output context, you place In <dimension_list> outside function parentheses. In the formula given above, the input and output contexts are as follows:

Input context

Output context

EXAMPLE Specifying an output context with In

You have a block based on the Island Resorts Marketing universe that shows customers Country, Region,City and Revenue; you want to include average revenue by Country and Region in the block. If you add a column with the formula Average(<Revenue>) the figures in this column are the same as those in the Revenue column. Why is this? This is because the blocks default output context is (Country,Region,City) and there is only one revenue figure for each country, region and city combination. As a result the average revenue is the same as the figure in the Revenue column. You need to specify an output context of (Country,Region) to calculate an average by country and region. The formula of the Average column is therefore Average(<Revenue> In (<Country of origin>,<Region>))

Understanding Calculation Contexts

BusinessObejcts Advanced Query Building Techniques Guide

21

This gives the following block:

You can see where the figures in the Average column come from by creating another block with a break on Country and Region and an average calculation in the break footer.

You can see that the averages in the footers correspond to the averages in the Average column in the previous block; BusinessObjects calculated those averages by ignoring the City dimension. Even such a simple example illustrates the power of calculation contexts. Simply to create the block BusinessObjects has resolved a complex series of joins and built the appropriate SQL to return revenue by country, region and city. But in addition to that you are able to aggregate at the country and region level in the

What is extended syntax?

22

BusinessObejcts Advanced Query Building Techniques Guide

same block. Even if the table structure behind this report were radically simplified, with all dimensions and revenue stored in one table, you would still need to use a correlated subquery to achieve the same result:
select country, region, city, revenue, (select avg (revenue) from geo g2 where g2.country = g1.country and g2.region = g1.region group by g2.country, g2.region) as sum_by_country_region from geo g1

EXAMPLE Specifying an input context with In

You have a block showing customers country, region city and revenue, and you want to add the maximum revenue for each Country/Region combination. The formula for the Max column in the block is

Understanding Calculation Contexts

BusinessObejcts Advanced Query Building Techniques Guide

23

Max(<Revenue> In (<Country of origin> ,<Region>))

You are unlikely to want to add columns to blocks as shown in the previous examples, but these examples show how you can use BusinessObjects to calculate at numerous different levels of aggregation within the same report by using context operators. One way you might use this is in an alerter.

What is extended syntax?

24

BusinessObejcts Advanced Query Building Techniques Guide

EXAMPLE Using context operators and variables to create an aleter

In this example you have a block showing customers country, region, city and revenues, and you want to show these rows in red where the maximum revenue by country and region is greater then $700,000. To do this, create a variable, MaxCountryRegion, with the formula Max(<Revenue> In (<Country of origin> ,<Region>)). You can now use this variable in the definition of an alerter:

Understanding Calculation Contexts

BusinessObejcts Advanced Query Building Techniques Guide

25

If you apply this alerter to each column, you can change the format of the column based on an aggregation that is different from the aggregation in the block.

It is this ability to work with data at different levels of aggregation simultaneously that gives context operators their power.

EXAMPLE Specifying and input and an output context with In

Formulas can contain both input and output contexts. In this example you have a block based on the eFashion universe and containing Year, Quarter, Month and Sales Revenue. You add an additional column with the formula Average(<Sales revenue> In (<Year> ,<Quarter>)) In <Year>

What is extended syntax?

26

BusinessObejcts Advanced Query Building Techniques Guide

What is this column showing? This formula tells BusinessObjects to take the average of the aggregated quarterly revenues. The input context, (<Year>,<Quarter>) tells BusinessObjects to aggregate revenues into quarterly totals. The output context, (<Year>) tells BusinessObjects to average these aggregated revenue across each year.

You can verify this by creating a break on Year and Quarter to simulate the input context (which says that Year and Quarter only are taken into account). The average of the sums that appears at the bottom of each block is 3,308,056 - the

Understanding Calculation Contexts

BusinessObejcts Advanced Query Building Techniques Guide

27

number that appears in the Quarterly Aggregate Average column above.

Remember that the output context is (<Year>), and the output context tells BusinessObjects to output the result as if it appeared in the footer of a break on the dimension(s) specified in the output context. This is why BusinessObjects averages the aggregate quarterly totals over the year. The ForEach context operator The ForEach operator tells BusinessObjects to add dimension(s) onto the default calculation context.
EXAMPLE Adding a dimension to the input context with ForEach

In this example, based on the eFashion universe, you have a block showing Year and Sales Revenue. The report microcube also contains the Quarter dimension, and you want to include a column that shows the smallest quarterly revenue for

What is extended syntax?

28

BusinessObejcts Advanced Query Building Techniques Guide

each year, but without including the Quarter dimension in the block. The formula is Min(<Sales revenue> ForEach <Quarter>). A column with this formula gives the following results:

You can verify the values in the MinByQuarter column by adding the Quarter dimension to the block, creating a break on (Year, Quarter) and inserting a Min calculation:

The ForAll context operator The ForAll context operator tells BusinessObjects to remove dimensions from the default calculation context.
EXAMPLE Removing a dimension from the input context with ForAll

In this example, based on the eFashion universe, you have a block showing Year, Quarter, Month Name and Sales Revenue. You want to add a column that shows the total Sales Revenue for each quarter. Using ForAll, the formula is

Understanding Calculation Contexts

BusinessObejcts Advanced Query Building Techniques Guide

29

Sum(<Sales Revenue> ForAll (<Month Name>)). In this situation, ForAll (<Month Name>) tells BusinessObjects to remove the Month Name dimension from the default input context (Year, Quarter, Month Name), giving the following result:

When to use ForEach and ForAll The ForEach and ForAll operators are useful when you have many dimensions in a calculation. If you have ten dimensions and you wish to calculate across nine of them, it is much simpler to remove the last dimension with ForAll than it is to specify the whole list explicitly.

What is extended syntax?

30

BusinessObejcts Advanced Query Building Techniques Guide

Extended syntax keywords


Extended syntax keywords allow you to refer to dimensions generically rather than through hard-coded lists. This has two main benefits: Future-proofing of reports Simplification of formulas

Future-proofing of reports
Reports change over time, and it is unlikely that a report will contain the same set of dimensions throughout its entire life-cycle. This can cause problems in reports that use extended syntax with explicitly-specified lists of dimensions.

Simplification of formulas
Formulas written with extended syntax keywords, especially formulas that contain many dimensions, are much easier to read and write when they use keywords.

List of keywords
The following table lists the extended syntax keywords and the data to which they refer: Keyword Body Can be used... Inside a block Outside a block Block Report CurrentPage Inside a block Anywhere Anywhere Refers to... The dimensions in the block The dimensions in the section All dimensions in the section All dimensions in the report The dimensions on the current page

Understanding Calculation Contexts

BusinessObejcts Advanced Query Building Techniques Guide

31

EXAMPLE Using keywords to avoid incorrect results

In this example you have a report showing Year, Quarter and Sales Revenue, and the block has an additional column showing each quarters sales revenue as a percentage of the total. The formula for this column, using keywords, is (<Sales revenue> In Body)/Sum(<Sales revenue> In Report) This generic formula tells BusinessObjects to divide the total revenue in the report by the revenue in the row, thus giving each revenue as a percentage of the total.

If you add a Month Name column to the report, the figures in the Percentage of Total column adjust automatically.

What if the formula had not been written generically, using keywords? For example: (<Sales revenue> In Body)/Sum(<Sales revenue> ForAll (<Year> ,<Quarter>)) Remember that the ForAll operator removes dimensions from the calculation context. By removing the Year and Quarter dimensions (the only dimensions in the report) you tell BusinessObjects to calculate a grand total for the whole report.

Extended syntax keywords

32

BusinessObejcts Advanced Query Building Techniques Guide

When you add the Month Name dimension to the block, however, the percentage totals are wrong:

Why is this? As long as the block contained only the Year and Quarter dimensions, the ForAll operator in the formula divisor summed across all revenues. But when the block contains Month Name, ForAll (<Year>,<Quarter>) removes Year and Quarter from the context, but leaves Month Name. The input context in the divisor therefore becomes Month Name, and the divisor, like the numerator (which by default returns the total for the row), returns the total for the month, which causes each percentage to be calculated as 100%.

Testing formulas with extended syntax


It is important to be sure that formulas that return extended syntax return correct results. In complex reports with many dimensions this can be difficult to verify. To test your figures, keep the following two rules in mind, and use these rules to build test reports. 1. The input context determines which dimensions go into the calculation; 2. The output context creates a break and aggregates totals as if they were in the break footer. This chapter applies these rules in several examples to verify the figures returned by formulas. See for example Adding a dimension to the input context with ForEach on page 27.

Understanding Calculation Contexts

BusinessObejcts Advanced Query Building Techniques Guide

33

EXAMPLE Creating a test report to verify a formula

This example shows how calculation contexts can operate at different levels behind the scenes to format a report, and how you can test that the behind-thescenes calculations are correct. The report shows customer countries, regions, cities and revenues by city, and highlights each row where the total regional revenue is greater than the average of all total regional revenues.

For example, the average of the summed regional revenues is 365,169; the total revenue for the Bavaria region is 783,520. Hence the rows showing cities in Bavaria are highlighted. The report has a variable, AverageByRegion, with the formula Average(Sum(<Revenue> ForAll(<City>))) In Report, which calculates the average of the summed regional revenues. This variable removes City from the input context of the Sum function, so revenues are summed by country and region. These sums are averaged, and the Report keyword is placed in the output context of the Average function so that the break occurs at the level of the whole report and the average returned is that of all the sums by region. The report contains another variable, SumByRegion, which calculates regional sums. This variable has the formula Sum(<Revenue> ForAll(<City>)).

Extended syntax keywords

34

BusinessObejcts Advanced Query Building Techniques Guide

NOTE

You could reference the SumByRegion variable in the AverageByRegion variable to simplfy it. In this case its formula becomes Average(<SumByCity>) In Report You use these two variables to create an alerter that highlights the appropriate rows.

How can you verify that the correct rows are highlighted? First, create a new report with a block showing Country, Region, City and Revenue. You know that the input context of the Sum function specifes the Country and Region dimensions, so create a section break on (Country, Region); now place a Sum calculation in the footer of each block. The input context for this Sum calculation is therefore (Country, Region); these sums are the sums returned by the SumByCity variable. Now, remember that the output context of the Average function is Report, so the break occurs at the level of the whole report. If you place the formula Average<Revenue> at the very bottom of the report, outside the sections, it returns the average of all the summed revenues, which gives 365,169. You can verify this figure against the summed revenues in each section and see that, for example, the revenue for West Japan (whose rows are not highlighted) is smaller, while the revenue for US South (whose rows are highlighted) is greater.

Understanding Calculation Contexts

Subqueries in BusinessObjects

chapter

36

BusinessObjects Advanced Query Building Techniques Guide

Overview
Subqueries are a powerful SQL feature that allows you to aggregate data at different levels within the same query. BusinessObjects allows you to work with subqueries in several ways: By specifying a subquery as a condition operand in the Query panel By specifying a Calculation in the Query Panel You can achieve the same result as a subquery by retrieving data at a low-level then aggregating it in BusinessObjects using extended calculation syntax. (See Understanding Calculation Contexts on page 15.) What makes subqueries different is the fact that you filter data on the database server rather than in BusinessObjects. Therefore, if the amount of data your reports are retreiving from the database is a concern, and you do not need to work with data at the lowest level of aggregation, you should consider using subqueries to pass the aggregation work over to the server, and to reduce the amount of data passed across the network.

Subqueries in BusinessObjects

BusinessObjects Advanced Query Building Techniques Guide

37

Using subqueries in the Query Panel


The simplest way to use a subquery is to select the Subquery operand type when building a query in the query panel.
EXAMPLE Show revenue by country and region where the country revenue > $1,000,000

In this example you have a report showing country, region and revenue and you want the report to return only those countries whose total revenue is greater than $1,000,000. You could do this using extended calculation syntax (Understanding Calculation Contexts on page 15) by creating an additional variable to calculate revenue by country, then filtering on this variable. The variable would have the formula Sum(<Revenue> In <Country>). In this approach BusinessObjects retrieves the data for all countries then filters at the client end. This is the appropriate approach if you also want to work with the data at lower levels of aggregation in the same report. If you do not, you should use a subquery. When you use a subquery, BusinessObjects generates SQL that filters the data at the database end before returning it to the client. To build this query using a subquery: 1. Drag the Country, Region and Revenue objects to the Result Objects pane of the Query Panel. 2. Drag the Country object to the Conditions pane (because you want to filter the data at source by country). 3. Select the Equal To operator. 4. Select the Create a Subquery (ANY) operator. The subquery appears as an additional tab on the Query Panel. 5. In the additional tab, drag the Country object to the Result Objects pane. 6. Drag the Revenue object to the Conditions pane and set up the query Revenue > 1000000 Run the query to return the query result.

Using subqueries in the Query Panel

38

BusinessObjects Advanced Query Building Techniques Guide

Comparing subqueries and extended calculation syntax


You can see the differences in the two approaches in the previous example by examining the SQL generated by the query. When you used extended syntax, BusinessObjects generated the following SQL:
SELECT Resort_Country.country, Resort.resort, sum(Invoice_Line.days * Invoice_Line.nb_guests * Service.price) FROM Country Resort_Country, Resort, Invoice_Line, Service, Service_Line WHERE ( Resort_Country.country_id=Resort.country_id ) AND ( Invoice_Line.service_id=Service.service_id ) AND ( Resort.resort_id=Service_Line.resort_id ) AND ( Service.sl_id=Service_Line.sl_id ) GROUP BY Resort_Country.country, Resort.resort

This SQL contains no restrictions on Country and returns three rows to BusinessObjects.

Subqueries in BusinessObjects

BusinessObjects Advanced Query Building Techniques Guide

39

When you use a subquery, the SQL looks like this:


SELECT Resort_Country.country, Resort.resort, sum(Invoice_Line.days * Invoice_Line.nb_guests * Service.price) FROM Country Resort_Country, Resort, Invoice_Line, Service, Service_Line WHERE ( Resort_Country.country_id=Resort.country_id ) AND ( Invoice_Line.service_id=Service.service_id ) AND ( Resort.resort_id=Service_Line.resort_id ) AND ( Service.sl_id=Service_Line.sl_id ) AND ( Resort_Country.country = ANY (SELECT Resort_Country.country FROM Country Resort_Country, Invoice_Line, Service, Service_Line, Resort WHERE ( Resort_Country.country_id=Resort.country_id ) AND ( Invoice_Line.service_id=Service.service_id ) AND ( Resort.resort_id=Service_Line.resort_id ) AND ( Service.sl_id=Service_Line.sl_id ) GROUP BY Resort_Country.country HAVING ( sum(Invoice_Line.days * Invoice_Line.nb_guests * Service.price) ) ) ) GROUP BY Resort_Country.country, Resort.resort

>=

1000000

In this case, BusinessObjects has added a subquery with grouping and a HAVING clause to the SQL, which means that the condition is applied on the database server and two rows only are returned to the client.

Using subqueries in the Query Panel

40

BusinessObjects Advanced Query Building Techniques Guide

Dimension restrictions in subqueries


Comparing dimensions In the previous example you compared the result of the subquery against the Country dimension. Note that if you attempt to drag more than one dimension to the Results Obejcts pane in the subquery tab, the Run button is disabled because the subquery can compare one dimension only. Note also that, although you can drag any dimension object to the Result Objects pane, the only object that makes sense is Country. It does not make sense to compare a list of countries against, for example, a list of regions. There will never be a match, and the query will never return any data.

Subqueries in BusinessObjects

BusinessObjects Advanced Query Building Techniques Guide

41

Creating subqueries by using complex conditions


Another way of building subqueries is by using complex conditions when you build your query in the Query Panel. Calculations are particularly powerful when used in conjunction with user objects. You can build a user object with an aggregate function, then determine in the calculation at which level the aggregate is to be calculated. A calculation consists of four componenents, each of which is defined by a step in the calculation wizard. 1. The dimension or measure used in the calculation 2. The grouping dimensions 3. The synchronizing dimensions 4. The number of values to compare.
EXAMPLE Return country, resort and revenue for those countries/resorts with higher than average revenue

This report should return the following data because the average revenue by country and resort is $1,095,508.

One way to do this is with a calculation. To do this: 1. Create a user object, Average Revenue, that calculates the average of the Revenue measure. 2. Drag the Revenue object to the Conditions pane in the Query panel. 3. Select the Greater than or equal to operator. 4. Select Calculation. The Complex Condition wizard appears at the Select an Object screen. You use the Select an Object screen to determine which dimension or measure is used in the comparison between the main query and the

Creating subqueries by using complex conditions

42

BusinessObjects Advanced Query Building Techniques Guide

subquery. 5. Select the Average Revenue user object.

6. Click Begin. The Define the Level of Calculation screen appears. You use this screen to set the grouping level in the subquery. 7. Click By one or more objects and select the Country and Resort dimensions.

Subqueries in BusinessObjects

BusinessObjects Advanced Query Building Techniques Guide

43

This means that the average revenue will be calculated by country and resort. 8. Click Next. The Synchronize Your Calculation screen appears. You use this dialog box to determine which (if any) dimensions in the subquery are correlated with dimensions in the main query. 9. Select Independently of all your objects. In this case you wish to calculate an overall average revenue, so the subquery should not be correlated.

10. Click Next. The Select the Number of Values to Compare screen appears. You use this screen to determine how the values returned by the subquery are compared against the main query. In this case the subquery returns one value only, so you can select either option. 11. Click Finish and run the report.

Creating subqueries by using complex conditions

44

BusinessObjects Advanced Query Building Techniques Guide

Subqueries in BusinessObjects

Working with Prompts

chapter

46

BusinessObjects Advanced Query Building Techniques Guide

Overview
Prompts allow you to make reports generic by giving the user the option to supply arguments when they run the report. There are several techniques you can use to enhance the basic prompts provided by BusinessObjects.

Working with Prompts

BusinessObjects Advanced Query Building Techniques Guide

47

Creating meaningful LOVs in prompts


You can use prompts to supply arguments to functions, but these arguments are not always meaningful to users. You can map these arguments to more user-friendly labels that are displayed in the prompt LOV by using the technique described below. The following example is based on Microsoft SQL Server and uses Transact-SQL. It also performs revenue calculation specific to the Island Resorts Marketing database. However, the general approach is adaptable to all DBMSs and databases.
NOTE

The BusinessObjects CD contains scripts and instructions for creating the eFashion and Island Resorts Marketing demo databases on SQL Server and Oracle.

Creating a Revenue by Day object


This example uses the Island Resorts Marketing Universe against a SQL Server database. You want to create an object that will show total revenue accrued on different days of the week. You can isolate different days using the Transact-SQL DATEPART function. For example, if the day in the invoice_date column of the SALES table is a Tuesday,
DATEPART (dw, sales.invoice_date) returns 3. In order to sum all invoices where the invoice date falls on a Tuesday, you include the condition WHERE DATEPART (dw, invoice_date) = 3 in the query SQL.

If you want the report user to be able to isolate particular days when summing revenue, you must give them the opportunity to supply the day number to the DATEPART function via a prompt. But from the users point of view, a list of numbers from 1 to 7 in a prompt LOV is not meaningful. You need to replace the numbers with the names of the days, then map these names to the numbers to be input to the function.

Mapping function arguments to labels


To create an object that shows a list of day names in a prompt, then converts these names to the numbers required by the function, do two things:

Creating meaningful LOVs in prompts

48

BusinessObjects Advanced Query Building Techniques Guide

1. Create a lookup table in the database that maps the day numbers to the day names. 2. Create a Revenue By Day object that prompts for day names then transforms these names to numbers using the lookup table.

Creating the lookup table


Your lookup table must contain two columns: one that contains the values input directly to the function, and another that maps these values to labels. In this case, create a table called DAYNAME with the columns day_num (of type integer) and day_name (of type varchar). The data in this table is as follows:
day_num 1 2 3 4 5 6 7 day_name Sunday Monday Tuesday Wednesday Thursday Friday Saturday

Working with Prompts

BusinessObjects Advanced Query Building Techniques Guide

49

Creating the object


You can now create the Revenue By Day object that uses this table. This objects Select is defined as
SUM(Invoice_line.days * Invoice_Line.nb_guests * Service.price) and its Where is defined as:
DATEPART (dw, Sales.invoice_date) in (select daynum from dayname where day_name in @Prompt('Choose a Day or Days' ,'a' ,{'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Sa turday'},multi,constrained))

Running a report
To run a report showing revenue by day, place the Revenue By Day object onto the report. To show revenue-by-day by resort, place the Resort and

Creating meaningful LOVs in prompts

50

BusinessObjects Advanced Query Building Techniques Guide

Revenue By Day objects onto the report. When you run the report, you are presented with the following prompt:

If you select, for example, Tuesday, Wednesday and Thursday from the list, the generated SQL is as follows:
SELECT Resort.resort, SUM(Invoice_line.days * Invoice_Line.nb_guests * Service.price) FROM Resort, Invoice_Line, Sales, Service, Service_Line WHERE ( Invoice_Line.inv_id=Sales.inv_id ) AND ( Invoice_Line.service_id=Service.service_id ) AND ( Resort.resort_id=Service_Line.resort_id ) AND ( Service.sl_id=Service_Line.sl_id ) AND ( DATEPART (dw, Sales.invoice_date) in (select daynum from dayname where day_name in (''Tuesday'' , ''Wednesday'' , ''Thursday'')) ) GROUP BY Resort.resort

Working with Prompts

BusinessObjects Advanced Query Building Techniques Guide

51

The object WHERE clause


The WHERE clause of the Revenue By Day object transforms the users selection(s) in the prompt LOV into the numbers required by the DATEPART function. It does this by selecting the value(s) from the day_num column in the DAYNAME table for the rows where the values in the day_name column match the LOV selections.

Creating meaningful LOVs in prompts

52

BusinessObjects Advanced Query Building Techniques Guide

Creating an ALL option in a prompt


Prompts allow users to select multiple options from a list. For example, a prompt might ask the user to select a country or countries. If the user wants to return data for all countries, they need to select every item in the list. This is feasible for a short list of values, but becomes impractical when the list of values grows. It is much more elegant to have an ALL option as a shorthand for every item in the list of values. This section shows how you can add an ALL option to a prompt. When the user selects ALL, BusinessObjects returns data as if the user had selected every item in the list of values. This technique has two steps: 1. Add ALL to an object list of values 2. Create a prompt using SQL CASE logic

Adding ALL to an object list of values


In the following example you add an ALL option to the Country of origin object in the Island Resorts Marketing database. The first thing you need to do is create a dummy table with one column and one row. (This dummy table is also used in advanced SQL generation; see Creating a dummy table on page 86.) The names of the table and column and the datatype of the one row of data are irrelevant. In this example, the table is called dummy, the column is col and it is populated with one integer.

Working with Prompts

BusinessObjects Advanced Query Building Techniques Guide

53

To add ALL to the Country of origin list of values, you modify the list of values definition in Designer. By default the list of values is simply the values returned by the Country of origin object itself, so the definition shows the object in the Result Objects pane of the Query Panel. To add ALL: 1. Create an additional object called ALL. This object simply selects the col column from the dummy table.

2. Select the Combine Queries option on the Query Panel to add an additional query to the definition of the Country of Origin list of values. Drag the ALL object to the Query Panel and relate this new query to the original list of values query by UNION. This means that the Country of Origin list of

Creating an ALL option in a prompt

54

BusinessObjects Advanced Query Building Techniques Guide

values now contains all the countries in the list, plus ALL:

Now you need to create an object that applies appropriate logic depending on whether the user selects ALL or a country or countries from the list. This CountryPrompt object selects the country column from the country table.

It is the WHERE clause of this object that performs the important processing.

Working with Prompts

BusinessObjects Advanced Query Building Techniques Guide

55

In full, the WHERE clause is as follows: country in (select case @Prompt('Choose a country or countries','a','Customer\Country of origin',multi,constrained) when 'ALL' then country else @Variable('Choose a country or countries') end) This SQL uses the CASE construction to test the user input and perform the appropriate processing. The prompt list of values is the Country of origin list of values (which now contains the ALL option.) If the user selects ALL then the subquery simply returns all countries in the list of countries (when ALL then country). If the user selects a country or countries, on the other hand, the subquery returns the list of countries they selected through the @Variable function. The ALL SQL is therefore: SELECT country FROM country WHERE country in (SELECT country from country) If the user selects the US and Holland, the SQL is: SELECT country FROM country WHERE country IN (US, Holland)

Creating an ALL option in a prompt

56

BusinessObjects Advanced Query Building Techniques Guide

Working with Prompts

Building Date-Related Queries

chapter

58

BusinessObjects Advanced Query Building Techniques Guide

Overview
Dates are a major component of any BusinessObjects report. This chapter shows a technique that allows you to answer sophisticated date-related questions. The technique involves adding a database table to your database. You then add universe objects that reference this table.

Building Date-Related Queries

BusinessObjects Advanced Query Building Techniques Guide

59

A technique for date-related queries


To use this technique, you add a table to your database that lists all possible dates within the periods covered by your reports. In the following examples this table is called dateset. The dateset table has one column, day_date., plus several other columns that split out the component parts of the date. (For example the year or the year + month concatenated into a string.) You can populate this table using a simple stored procedure, as follows:
create procedure sp_pop_dateset ( @start_date datetime ,@end_date datetime ) as begin create table dateset ( day_date day_date_year day_date_month

datetime, integer, integer, day_date_day integer, day_date_dayofweek integer, day_date_yearmonth char(6), constraint pk_dateset primary key (day_date)

) declare @date datetime select @date = @start_date while @date <= @end_date begin insert into dateset ( day_date, day_date_year, day_date_month, day_date_day, day_date_dayofweek, day_date_yearmonth ) select @date, datepart (year, @date), datepart (month, @date), datepart (day, @date), datepart (dw, @date), convert (char(4), year(@date)) + case len (month (@date))

A technique for date-related queries

60

BusinessObjects Advanced Query Building Techniques Guide

when 1 then 0 + convert (char(1), month(@date)) else convert (char(2), month(@date)) end

select @date = dateadd (day, 1, @date) end end

You should include all dates that are likely to be covered in your BusinessObjects reports in the dateset table.

Building Date-Related Queries

BusinessObjects Advanced Query Building Techniques Guide

61

Using the dates table


The dates table is extremely powerful, and you can use SQL to answer many date-related questions, as the following examples show.
EXAMPLE Return all leap years

The SQL for this is straightforward: select day_date_year from dateset where day_date_month = 2 and day_date_day = 29 group by day_date_year ,day_date_month

EXAMPLE How many Fridays are in each month?

To answer this query you use grouping and counting: select day_date_yearmonth day_date_month, count (1) from where dateset day_date_dayofweek = 5 day_date_month

group by day_date_year,

A technique for date-related queries

62

BusinessObjects Advanced Query Building Techniques Guide

EXAMPLE Return all dates in all months that begin with a Thursday

In this SQL takes advantage of the year_month column, which concatenates the year and month of the date into a string. The subquery returns the year/month strings of those months that begin with a Thursday. The outer query returns all dates in those years/months: select day_date from dateset where day_date_yearmonth in ( select day_date_yearmonth from where and dateset day_date_dayofweek = 5 day_date_day = 1 )

EXAMPLE Return the last day of each month in the year 2000

This query also uses aggregation and grouping: select max (day_date) from where dateset datepart (year, day_date) = 2000 datepart (month, day_date)

group by datepart (year, day_date),

Creating universe objects


As these examples show, the dates table is an extremely powerful tool for answering date-related questions. You can work with it by building a free-hand SQL data provider, then linking this data provider with other queries. To make your date handling more BusinessObjects-specific, you can create date-related objects in the universe and then use these objects in your queries.

Building Date-Related Queries

BusinessObjects Advanced Query Building Techniques Guide

63

EXAMPLE Show revenue and include only those months that end on a particular day or days in the calculation

In this example you will build a report showing country, region and revenue, but include only those invoices that occurred in a month that ends on a particular day(s) (selected by the user) and in a particular year (also selected by the user). To build this query you need an object (in this example called Months beginning with ?) that returns all dates that end with the day. You will then use this object in a subquery. To build the object: 1. Select dateset.day_date in the Select box of the Edit Properties Of dialog box. (This SELECT statement is identical for all date objects; it is the WHERE clause is the place where the real interest occurs.) 2. Type the following SQL in the Where clause of the Edit Properties Of dialog box: day_date_year in @Prompt('Choose a year or years' ,'n' ,'DateObjects\CountryPrompt',multi,constrained) and day_date_yearmonth in (select day_date_yearmonth from dateset d2 where day_date_dayofweek in (select day_num from dayname where day_name in @Prompt('Choose a last day(s)' ,'a' ,{'Sunday','Monday','Tuesday','Wednesday','Thursday','Fr iday','Saturday'},multi,constrained)) and day_date_day = ( select max (day_date_day) from dateset d3 where

A technique for date-related queries

64

BusinessObjects Advanced Query Building Techniques Guide

d3.day_date_year = d2.day_date_year and d3.day_date_month = d2.day_date_month))

When you drop this object onto a report and run the report, you see the following prompt:

Building Date-Related Queries

BusinessObjects Advanced Query Building Techniques Guide

65

You use this prompt to select the last day(s) and the years. When you click Values and the cursor is in the Choose a last day(s) box, you see a list of days:

When the cursor is in the Choose a year or years box, you see a list of years:

When you run the report, the object returns all the dates in all the months that end with the day(s) you selected and that occur in the month(s) you selected.

A technique for date-related queries

66

BusinessObjects Advanced Query Building Techniques Guide

Lets take a close look at the object WHERE clause, which uses nested subqueries to do the work. The prompt in the first subquery uses a lookup table that returns the names of the days of the week. (This technique is described in more detail in the section Creating meaningful LOVs in prompts on page 47.) in the chapter Working with Prompts.) The lookup table maps the day name to its number to compare it against the day_date_dayofweek column, which contains the day number. There is a further subquery to find the last day of the month [select max(day_date_day)...] The result of these two subqueries is that the list of dates whose day_date_yearmonth column corresponds to the year/month of the months whose last day falls on the day chosen by the user. You can now use the list of dates returned by the Months beginning with ? object in a subquery. Place the Country, Region and Revenue objects in the report, then place create a subquery condition on the Invoice Date object. If you restrict the values of Invoice Day to those days returned by Months beginning with ?, the report shows only those revenues generated in months ending with the day(s) you specified.

EXAMPLE Show revenue and include only those months that begin on a particular day or days in the calculation

This example is almost identical to the previous example, except that you specify SELECT min (day_date_day) in the second subquery in the Where clause to return the first day of the month rather than the last. The Where clause SQL is as follows: day_date_year in @Prompt('Choose a year or years' ,'n' ,'DateObjects\CountryPrompt',multi,constrained) and day_date_yearmonth in (select day_date_yearmonth from dateset d2 where day_date_dayofweek in (select day_num from dayname where day_name in @Prompt('Choose a last day(s)' ,'a' ,{'Sunday','Monday','Tuesday','Wednesday','Thursday','Frid ay','Saturday'},multi,constrained)) and day_date_day = ( select min (day_date_day) from dateset d3 where d3.day_date_year = d2.day_date_year and . d3.day_date_month = d2.day_date_month))

Building Date-Related Queries

BusinessObjects Advanced Query Building Techniques Guide

67

EXAMPLE Show revenue and include only those months that contain X occurrences of day Y

In this example you want to restrict revenue calculations to those months in which, for example, Tuesday occurred four times. In this instance you create an object, Day X occurs Y times. As always, the object Select clause is simply the day_date column from the dateset table, and the WHERE clause does the work. The WHERE clause in this case is: dateset.day_date_yearmonth in (select day_date_yearmonth from dateset d2 where day_date_dayofweek in (select day_num from dayname where day_name in @Prompt('Choose the day' ,'a' ,{'Sunday','Monday','Tuesday','Wednesday','Thursday','Frid ay','Saturday'},multi,constrained)) group by day_date_yearmonth having count(*) = @Prompt('Choose the number of occurrences' ,'n' ,{'3','4','5'},mono,constrained)) Once again, this WHERE clause uses a prompt that allows the user to select the day name. The other prompt allows the user to select the number of occurences of the day. When the user runs the query, they see the following dialog box:

The SQL filters on the users choice of day as described in the previous examples. To filter on the number of occurrences, the second prompt is matched against the output of the HAVING clause. Stripped of BusinessObjects prompt syntax, the SQL reads as follows: SELECT day_date FROM dateset WHERE day_date_yearmonth IN( SELECT day_date_yearmonth FROM dateset d2 WHERE d2.day_date_dayofweek = [user_choice]

A technique for date-related queries

68

BusinessObjects Advanced Query Building Techniques Guide

GROUP BY day_date_yearmonth HAVING COUNT (*) = [user_choice])

Accounting for holiday days


As well as working with days of the week, you might also be interested in analyzing the impact of public holidays. You can do this by adding a holiday_flag column to the table, which is set to 0 (when the day is not a public holiday) or 1 (when it is). If you want to return all dates in months that have at least one public holiday, the SQL is as following: SELECT day_date_yearmonth FROM dateset WHERE day_date_yearmonth IN ( SELECT DISTINCT d2.day_date_yearmonth FROM dateset d2 WHERE holiday_flag = 1 GROUP BY d2.day_date_yearmonth HAVING COUNT (holiday_flag) > 0 Once again, you can adapt this SQL to a Designer object, as the following example shows.
EXAMPLE Return all dates in months that have X public holidays

To do this, create an object called Months with X public holidays. The WHERE clause of this object is as follows: day_date_yearmonth in (select distinct day_date_yearmonth from where dateset holiday_flag = 1

group by day_date_yearmonth having count (holiday_flag) = @Prompt('Choose the number of public holidays' ,'n' ,{'1','2','3'},mono,constrained)) When the user runs a query that uses this object they see a prompt that allows them to restrict the dates returned to those falling in months where a certain number of public holidays occur.

Building Date-Related Queries

BusinessObjects Advanced Query Building Techniques Guide

69

A technique for date-related queries

70

BusinessObjects Advanced Query Building Techniques Guide

Building Date-Related Queries

Working with Hierarchies

chapter

72

BusinessObjects Advanced Query Building Techniques Guide

Overview
Relational databases often model hierarchies. This chapter describes some techniques for working with hierarchies in BusinessObjects.

Working with Hierarchies

BusinessObjects Advanced Query Building Techniques Guide

73

Hierarchies in relational databases


Hierarchies in relational databases are usually modelled as a series of parent and child tables, with each child connected to its parent by a foreign key. For example, in the Island Resorts Marketing database, the Country, Region and City tables model a geographical hierarchy:

To work with a hierarchy it is often useful to return the entire hierarchy in one result set.

Hierarchies in relational databases

74

BusinessObjects Advanced Query Building Techniques Guide

Building a hierarchy result set


You can build a hierarchy result set against the Island Resorts Marketing database by creating a free-hand SQL data provider based on the following SQL query:
select country as hierarchy_country, NULL as hierarchy_region, NULL as hierarchy_city, 0 as item_level, country as order_col from country union select c.country as hierarchy_country, region as hierarchy_region, NULL as hierarchy_city, 1 as item_level, c.country + r.region as order_col from region r, country c where c.country_id = r.country_id union select c2.country as hierarchy_country, r.region as hierarchy_region, c.city as hierarchy_city, 2 as item_level, c2.country + r.region + c.city as order_col from city c, region r, country c2 where r.region_id = c.region_id and r.country_id = c2.country_id

Lets examine this query in detail. It returns five columns: hierarchy_country, hierarchy_region, hierarchy_city, item_level and order_col. The hierarchy_ columns return the names of the countries, regions and cities in the hierarchy, or NULL when an item is not relevant at a particular level. (For example, the Country level returns NULL for region and city.) The item_level column returns the items level in the hierarchy (country at level 0, region at 1 and city at 2). The order_pos column returns a concatenation of all the hierarchy items: for example Australia for Australia, AustraliaQueensland for Queensland and AustraliaQueenslandBrisbane for Brisbane. You will use this column to sort the result set. In general, this approach - creating a hierarchy result set through a set of UNIONed SQL queries - is useful to flatten any multitable hierarchy into a single table.

Working with Hierarchies

BusinessObjects Advanced Query Building Techniques Guide

75

Displaying the hierarchy in BusinessObjects


You can use this result set to display an attractively-formatted hierarchy in BusinessObjects. When you run the query, the data appears as follows:

How can you turn this into a formatted hierarchical display? The following example shows the process.
EXAMPLE Creating a formatted hierarchy in BusinessObjects

The first thing to do is to sort the block on the order_col column to arrange the hierarchy items in their correct order, Next, create an object that will show the items with the classic indentation structure that is often used to display hierarchies (for example in Windows Explorer) and place it in the block. The formula for this object, item_indented, makes use of the item_level column to indent the item and to determine whether to use the hierarchy_country, hierarchy_region or hierarchy_city item in the display: =Left(" " ,2*<item_level>) + If <item_level>=0 Then <hierarchy_country> Else If <item_level>=1 Then <hierarchy_region> Else <hierarchy_city>

Hierarchies in relational databases

76

BusinessObjects Advanced Query Building Techniques Guide

The result is as follows:

At this point you can hide all columns except for hierarchy_display, then use the item_level column to format the hierarchy_display column with an alerter. For example, you can apply the following alerter:

Working with Hierarchies

BusinessObjects Advanced Query Building Techniques Guide

77

This alerter produces the following display:

Adding measures to the hierarchy


So far you have created a formatted hierarchy display, which could be useful in its own right, but which is more likely to have measures associated with it. How can you add a revenue measure to the display so that it will calculate the revenue at the correct aggregation level, depending on the row? (For example, total revenue for France on the France row; revenue for French Alps only on the French Alps row.)
EXAMPLE Adding measures to a hierarchy

For this you need to add an additional data provider to the report. This data provider is based on the Island Resorts Marketing universe and contains the same dimensions that appear in the hierarchy (Country of origin, Region and City) as well as the Revenue measure object.

Hierarchies in relational databases

78

BusinessObjects Advanced Query Building Techniques Guide

Now you need to link the dimensions in this second data provider (called Revenue) to the equivalent dimensions in the first data provider (called Hierarchy) as follows: Dimension in Hierarchy data provider hierarchy_country hierarchy_region hierarchy_city Linked dimension in Revenue data provider Country of origin Region City

The final step is to create a variable, hierarchy_revenue, that calculates the revenue for each item in the hierarchy. The formula for this variable is: If <item_level> = 0 Then Sum (<Revenue> In <hierarchy_country>) Else If <item_level> = 1 Then Sum (<Revenue> In (<hierarchy_country> ,<hierarchy_region>)) Else Sum (<Revenue> In (<hierarchy_country> ,<hierarchy_region> , <hierarchy_city>)) This formula uses the If Then Else construction to check the level of each item in the hierarchy (by checking the value of the item_level variable). It then uses extended calculation syntax to aggregate the revenue at the appropriate level, as shown in the following table. (For more information about extended calculation syntax see Understanding Calculation Contexts on page 15.) Level Country Region City Calculation input context hierarchy_country hierarchy_country, hierarchy_region hierarchy_country, hierarchy_region, hierarchy_city By using extended calculation syntax, you ensure that you need retrieve the revenue from the database once only, at the lowest level of detail. Subsequently you aggregate the revenue at different levels in BusinessObjects.

Working with Hierarchies

BusinessObjects Advanced Query Building Techniques Guide

79

When you add the hierarchy_revenue variable to the report it appears as follows:

Note that BusinessObjects automatically takes care of the outer join that occurs between the two data providers. BusinessObjects still returns the entire hierarchy, even for those countries, regions and cities that do not have associated revenue. It is often better to simulate an outer join by linking data providers at the BusinessObjects level rather than defining outer joins in the universe at the Designer level, because outer joins add additional design constraints to the universe.

Hierarchies in relational databases

80

BusinessObjects Advanced Query Building Techniques Guide

Reporting at different levels of the hierarchy


One of the advantages of this kind of hierarchical display is the ability to report on several levels of the hierarchy simultaneously. You have already seen how you can display revenue for countries, regions and cities in the same column by creating a separate data provider and using extended calculation syntax. You can do this with many different sorts of calculations.
EXAMPLE Adding an alerter to a hierarchy

In this example you want to add an alerter to the hierarchy that will highlight each revenue figure that is below the average revenue for items at that level. (For example, country revenues that are lower than the average revenue per country.) To do this, create a variable, average_level_revenue, that calculates the average revenues for each item in the hierarchy. The formula for this variable is: If <item_level> = 0 Then Average(<Revenue> In <hierarchy_country>) In Block Else If <item_level> = 1 Then Average(<hierarchy_revenue> In (<hierarchy_country> ,<hierarchy_region>)) In Block Else Average(<hierarchy_revenue> In (<hierarchy_country> ,<hierarchy_region> , <hierarchy_city>)) In Block Once again, this formula uses extended syntax to calculate at different levels of aggregation. You can now add the following alerter to highlight below-average revenues:

Working with Hierarchies

BusinessObjects Advanced Query Building Techniques Guide

81

The result is as follows:

This block shows that, for example, the revenue for the US ($1,186,257) is higher than the average revenue per country ($1,120,253); whereas the revenue for Germany ($1,054,248) is lower.

Hierarchies in relational databases

82

BusinessObjects Advanced Query Building Techniques Guide

Working with Hierarchies

Advanced SQL Generation

chapter

84

BusinessObjects Advanced Query Building Techniques Guide

Overview
This chapter deals with advanced SQL generation techniques in Designer that you can use to create objects tailored to your needs.

Advanced SQL Generation

BusinessObjects Advanced Query Building Techniques Guide

85

SQL generation in Designer


When you create an object in Designer, you work with two dialog boxes to define the object SQL: The Edit Properties of dialog box and the Tables dialog box. In the first of these dialog boxes you enter the SELECT statement in the Select box and the WHERE clause in the Where box. You use the Tables dialog box to determine which tables will appear in the FROM clause. For example, the Region object in the Island Resorts Marketing universe references the Region column of the Region table in the SELECT box, and the Region table in the Tables dialog box.

If you add a WHERE that restricts the regions to West, the generated SQL looks like this:
SELECT Region.region FROM Region WHERE ( Region.region = 'West'

From this you can see that the text in the SELECT box appears in the SELECT statement, the text in the WHERE box appears, enclosed in parentheses, in the WHERE clause, and the selected tables appear in the FROM clause. Because you must always select a table or tables, this means that SQL statements generated by Designer always contain a SELECT and FROM keyword. You cannot

SQL generation in Designer

86

BusinessObjects Advanced Query Building Techniques Guide

construct objects based on arbitrary SQL queries of your own design that do not conform to this base pattern. Or can you? In fact you can often trick Designer into building the SQL you want.

Creating a dummy table


What if you want to create universe objects that return the values of database server in-built variables? For example, a ServerVersion object that returns the value of the SQL Server @@VERSION variable. The select statement that you would normally use is SELECT @@VERSION. But Designer objects must reference a table; if they do not you receive the error message The query does not reference a table when you try to use them in BusinessObjects. To get around this, you build a dummy table with one column and one row. The table data is never referenced in your queries; it simply exists to fill out the SQL of queries that do not strictly speaking need to reference a table. If this table is called DUMMY and has one column, col, containing one row of data (the datatype of this column and the data in its one row are not important), the SQL becomes SELECT @@VERSION FROM DUMMY You define a ServerVersion object as follows:

Advanced SQL Generation

BusinessObjects Advanced Query Building Techniques Guide

87

Including and ORDER BY clause in generated SQL


How can you include other clauses such as ORDER BY and GROUP BY in SQL generated by Designer? What if you want to create an object that returns all the distinct invoice years in the Island Resorts Marketing database, sorted in ascending order by the database? The SQL to do this is:
SELECT DISTINCT datepart (year, invoice_date) as invoice_year FROM sales ORDER BY invoice_year

At first glance there appears to be no way of generating this SQL from the Edit Properties Of dialog box. But the important thing to remember is that the only client-side validation that BusinessObjects performs is to check that you have selected a table in the Tables dialog box. Apart from that, Designer builds the SQL based on the contects of the Select and Where boxes and sends it to the database for validation. It is the database that determines whether the generated SQL is valid. Bearing this in mind, you can force Designer into generating the SQL you are looking for. The SELECT clause presents no problem: simply type DISTINCT datepart (year, invoice_date) as invoice_year and Designer prefixes this with the SELECT keyword. The table list is equally straighforward; simply select the sales table from the list. It is the WHERE clause that presents the difficulty. In fact, this query does not need a WHERE clause. It does, on the other hand, need an ORDER BY clause, and the Where box is the only place to put it. The following text in the Where box solves the problem: 1=1 ) order by invoice_year -Remember that Designer places parentheses around the WHERE clause by default. You need to supply your own WHERE condition that will always be satisfied (1=1) and follow it with a bracket to close the parentheses. Now you can add the ORDER BY clause. (Note that you can reference the invoice_year alias created in the Select box because Designer sends off the whole generated SQL to the database for validation.) Finally you need to deal with the closing bracket that Designer adds around the WHERE clause. (As far as Designer is concerned, everything in the Where box is the WHERE clause.) You can remove this by prefixing it with a comment mark, --, to cause the database to ignore it.

SQL generation in Designer

88

BusinessObjects Advanced Query Building Techniques Guide

Designer generates the following SQL based on the text you typed in the Edit Properties Of dialog box: SELECT distinct datepart (year, invoice_date) as invoice_year FROM Sales WHERE ( 1=1 ) order by invoice_year -) This SQL returns the pre-sorted list of invoice years.

Using derived tables


Derived tables are an extremely powerful feature introduced in Designer 6.5. They allow you to build your own SQL queries which Designer then treats as if they were database tables. This feature takes advantage of SQL inline aliases, and means that you can build SQL of arbitrary complexity to return result sets whose columns you can use to build Designer objects.

What are inline aliases?


Inline aliases allow you to alias a block of SQL within a larger query and than select columns from that block. For example, the SQL to return the names of user-created tables in a SQL Server database is SELECT name FROM sysobjects WHERE type = u This could be expressed, using an inline alias, as SELECT * FROM ( SELECT name FROM sysobjects WHERE type = U ) sysobjects_alias where the original query is aliased as sysobjects_alias.

Inline aliases and derived tables


When you build an SQL query for an inline alias, Designer places this SQL within an aliased block and treats the columns returned as columns in a derived table.

Advanced SQL Generation

BusinessObjects Advanced Query Building Techniques Guide

89

EXAMPLE Using a derived table to build a visual hierarchy

In this example you use a derived table to build the visual hierarchy that you built earlier using free-hand SQL (see Working with Hierarchies on page 71.) The difference here is that you build Designer objects to create the hierarchy, rather than building it directly with a free-hand SQL query. (For a one-off report the freehand SQL solution is fine, but if multiple users need the same capability it makes sense to migrate it back to the Designer level.) The hierarchy, which displays customer locations in the Island Resorts Marketing database, appears as follows: :

SQL generation in Designer

90

BusinessObjects Advanced Query Building Techniques Guide

The first thing you need to do is to build the SQL that will return a result set showing all the hierarchy items, their level in the hierarchy, and their sort order. The following SQL does this:
select country as hierarchy_country, NULL as hierarchy_region, NULL as hierarchy_city, 0 as item_level, country as order_col from country union select c.country as hierarchy_country, region as hierarchy_region, NULL as hierarchy_city, 1 as item_level, c.country + r.region as order_col from region r, country c where c.country_id = r.country_id union select c2.country as hierarchy_country, r.region as hierarchy_region, c.city as hierarchy_city, 2 as item_level, c2.country + r.region + c.city as order_col from city c, region r, country c2 where r.region_id = c.region_id and r.country_id = c2.country_id

Advanced SQL Generation

BusinessObjects Advanced Query Building Techniques Guide

91

You create a derived table by selecting Derived Table from the Insert menu in Designer, and typing the SQL and table name. The table name is the alias that Designer uses when building the SQL.

When you click OK, Designer adds the table (in this case called hierarchy) with the columns specified in the SQL.

You can now use this table as you would any nornal table to create objects. To build a hierarchy you need to create an object for each column in the table:

SQL generation in Designer

92

BusinessObjects Advanced Query Building Techniques Guide

When you create these objects, hierarchy appears in the list of tables in exactly the same way as the physical database tables. When Designer generates the SQL for an object, it aliases the SQL used to build the derived table with the name of the derived table. For example, the SQL for the hierarchy_country object is as follows: SELECT hierarchy.hierarchy_country FROM (derived_table_sql) hierarchy You can now build a visual hierarchy using these objects. The approach is the same as you used with free-hand SQL in the chapter Working with Hierarchies on page 71. See that chapter for more detailed explanations of the steps in the following procedure. To build a hierarchy using the objects you have created: 1. Create a block using all the hierarchy objects. Designer generates the following SQLto build the block: SELECT hierarchy.hierarchy_country, hierarchy.hierarchy_region, hierarchy.hierarchy_city, hierarchy.item_level, hierarchy.order_col FROM ( derived_table_sql) hierarchy 2. Sort the table on the order_col column. 3. Create a hierarchy_display object that indents the objects in the hierarchy. 4. Delete all columns in the block except for hierarchy_display. 5. Create an alerter to format the rows depending on the object level in the hierarchy.

Advanced SQL Generation

BusinessObjects Advanced Query Building Techniques Guide

93

Index
B
Business Objects consulting services 11, 13 documentation 10 Documentation Supply Store 9 support services 11 training services 11, 13

I
input contexts defined 18

K
Knowledge Base 12

C
calculation context defined 17 consultants Business Objects 11 customer support 11

M
multimedia quick tours 10

O
Online Customer Support 11 output contexts defined 19

D
demo materials 9 Developer Suite 10, 12 documentation CD 9 feedback on 10 on the web 9 printed, ordering 9 roadmap 9 search 9 Documentation Supply Store 9

S
search documentation 9 support customer 11

T
Tips & Tricks 10 training on Business Objects products 11

E
education see training extended calculation syntax defined 18

W
web customer support 11 getting documentation via 9 useful addresses 12

F
feedback on documentation 10

Index

94

BusinessObjects Advanced Query Building Techniques Guide

Index

Anda mungkin juga menyukai