94
7/30/2019 Business Objects - Advanced http://slidepdf.com/reader/full/business-objects-advanced 1/94 BusinessObjects Advanced Query Building Techniques Guide BusinessObjects 6.5 Windows

Business Objects - Advanced

Embed Size (px)

Citation preview

Page 1: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 1/94

BusinessObjects Advanced Query Building

Techniques Guide

BusinessObjects 6.5

Windows

Page 2: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 2/94

Page 3: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 3/94

BusinessObjects Advanced Query Building Guide 3

Contents

Contents

Contents 3

Examples 5

Preface Maximizing Your Information Resources 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

Page 4: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 4/94

4 BusinessObjects Advanced Query Building Guide

Contents

Index 93

Page 5: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 5/94

BusinessObjects Advanced Query Building Guide 5

DRAFT Examples

Examples

Specifying an output context with In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

Specifying an input context with In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Using 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,00037

Return country, resort and revenue for those countries/resorts with higher thanaverage 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 . . . . . . . . . . . . . . . . . . 62Show 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

Page 6: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 6/94

6 BusinessObjects Advanced Query Building Guide

Examples DRAFT

Page 7: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 7/94

   p   r   e     f   a   c   e

Maximizing Your InformationResources

Page 8: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 8/94

8 BusinessObjects Advanced Query Building Guide

Maximizing Your Information Resources

Overview

Information, services, and solutions

The Business Objects business intelligence solution is supported by thousandsof 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 ontroubleshooting and best practices, this comprehensive documentation setprovides concrete solutions to your business problems.

Business Objects also offers a complete range of support and services to helpmaximize the return on your business intelligence investment. See in thefollowing sections how Business Objects can help you plan for and successfully

meet your specific technical support, education, and consulting requirements.

Page 9: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 9/94

BusinessObjects Advanced Query Building Guide 9

Information resources

Information resources

Whatever your Business Objects profile, we can help you quickly access thedocumentation and other information you need.

Where do I start?

Below are a few suggested starting points; there is a summary of useful webaddresses on page 12.

Documentation Roadmap

The Documentation Roadmap references all Business Objects guides andmultimedia, and lets you see at a glance what information is available, fromwhere, 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 areusing. Online help, multimedia, and guides in Adobe PDF format are availablefrom the product Help menus.

Documentation on the web

The full electronic documentation set is available to customers with a validmaintenance agreement on the Online Customer Support (OCS) website atwww.businessobjects.com/services/support.htm

Buy printed documentation

You can order printed documentation through your local sales office, or from theonline Business Objects Documentation Supply Store atwww.businessobjects.com/services/documentation.htm

Search the Documentation CD

Search across the entire documentation set on the Business ObjectsDocumentation CD shipped with our products. This CD brings together the full setof documentation, plus tips, tricks, multimedia tutorials, and demo materials.

Order the Documentation CD online, from the Business Objects DocumentationSupply Store, or from your local sales office.

Page 10: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 10/94

10 BusinessObjects Advanced Query Building Guide

Maximizing Your Information Resources

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 OnlineCustomer 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 thesites listed below for the latest documentation, samples, and tips.

Tips & Tricks

Open to everyone, this is a regularly updated source of creative solutions to anynumber of business questions. You can even contribute by sending us your owntips.

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 – inseven languages – on the Online Customer Support (OCS) website.

Developer Suite Online

Developer Suite Online provides documentation, samples, and tips to thosecustomers with a valid maintenance agreement and a Developer Suite licensevia the Online Customer Support (OCS) website.

Send us your feedback

Do you have a suggestion on how we can improve our documentation? Is theresomething you particularly like or have found useful? Drop us a line, and we willdo our best to ensure that your suggestion is included in the next release of our documentation: [email protected]

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

Page 11: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 11/94

BusinessObjects Advanced Query Building Guide 11

Services

Services

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

How we can support you?

Business Objects offers customer support plans to best suit the size andrequirements of your deployment. We operate three global customer supportcenters:

•  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 currentmaintenance agreement, and provides the most up-to-date Business Objectsproduct and technical information. You can log, update, and track cases from thissite 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 WorldwideCustomer 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 stageto the delivery of your deployment project. Expertise is available in relational andmultidimensional 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. Findmore information on the Business Objects Education website:www.businessobjects.com/services/education.htm

Page 12: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 12/94

12 BusinessObjects Advanced Query Building Guide

Maximizing Your Information Resources

Useful addresses at a glance

Address Content

Business Objects Documentation

www.businessobjects.com/services/documentation.htm

Overview of Business Objects documentation. Linksto Online Customer Support, Documentation Supply

Store, Documentation Roadmap, Tips & Tricks,Documentation mailbox.

Business Objects Documentationmailbox

[email protected]

Feedback or questions about documentation.

Product documentation

www.businessobjects.com/services/support.htm

The latest Business Objects product

documentation, to download or view online.

Business Objects product information

www.businessobjects.com

Information about the full range of BusinessObjects products.

Developer Suite Online

www.techsupport.businessobjects.com

 Available to customers with a valid maintenanceagreement and a Developer Suite license via theOnline Customer Support (OCS) website. Providesall the documentation, latest samples, kits and tips.

Knowledge Base (KB)

www.techsupport.businessobjects.com

Technical articles, documents, case resolutions.

 Also, use the Knowledge Exchange to learn whatchallenges other users – both customers andemployees – face and what strategies they find to

address complex issues. From the KnowledgeBase, click the Knowledge Exchange link.

Tips & Tricks

www.businessobjects.com/forms/tipsandtricks_login.asp

Practical business-focused examples.

Page 13: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 13/94

BusinessObjects Advanced Query Building Guide 13

Useful addresses at a glance

Online Customer Support

www.techsupport.businessobjects.com

www.businessobjects.com/services

Starting point for answering questions, resolvingissues.

Information about registering with WorldwideCustomer Support.

Business Objects Education Services

www.businessobjects.com/services/education.htm

The range of Business Objects training options andmodules.

Business Objects Consulting Services

www.businessobjects.com/services/consulting.htm

Information on how Business Objects can helpmaximize your business intelligence investment.

Address Content

Page 14: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 14/94

14 BusinessObjects Advanced Query Building Guide

Maximizing Your Information Resources

About this guide

This guide describes advanced query-building techniques usingBusinessObjects 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 Indicates

Small capitals The names of all products such asBusinessObjects, WebIntelligence, Supervisor,and Designer.

This font 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.

Some code  

more code

Placed at the end of a line of code, the symbol ( )indicates that the next line should be entered

continuously with no carriage return.

$DIRECTORYPATHNAME The path to a directory in the Business Objectsinstallation/configuration directory structure. For example:

• $INSTALLDIR refers to the Business Objectsinstallation directory.

• $LOCDATADIR refers to a subdirectory of the

BusinessObjects installation directory calledlocData.

Page 15: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 15/94

   c     h   a   p    t   e

   r

Understanding CalculationContexts

Page 16: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 16/94

16 BusinessObejcts Advanced Query Building Techniques Guide

Understanding Calculation Contexts

Overview

Extended calculation syntax is one of BusinessObjects’ most powerful yet leastunderstood 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 aggregationin a report. For example, in the same report you can show sales revenue byquarter and by year.

 Aggregation at different levels is much more difficult with SQL statementsbecause each statement can contain one GROUP BY clause only. Toaccomplish at the database level what you can accomplish simply inBusinessObjects 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)

Page 17: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 17/94

BusinessObejcts Advanced Query Building Techniques Guide 17

Defining the calculation context

Defining the calculation context

What are calculation contexts?

Calculation contexts give you more control over how a formula or measure isevaluated. To understand them, you need to be familiar with basic reportconcepts. 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 inrelation 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 thedimensions with which it is associated; in other words, on the context in which itis placed. BusinessObjects places measures in default contexts depending on

where they appear in a report, but you can change these defaults. This is what ismeant by defining the calculation context.

You can see default contexts by creating a block based on the eFashion universethat contains Year and Sales Revenue objects. In this case the Sales Revenueobject returns the revenue by year, because revenue is evaluated in the contextof the Year dimension. If you then add the Quarter dimension to the block, thefigures in the Sales Revenue column change because the default context is nowYear and Quarter.

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

Page 18: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 18/94

18 BusinessObejcts Advanced Query Building Techniques Guide

Understanding Calculation Contexts

 What is extended syntax?

Extended syntax allows you to specify calculation contexts explicitly, whichmeans that you do not need to accept BusinessObjects defaults. To useextended 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 formula’s input and output contexts determine what number themeasure or formula returns. You use extended syntax to specify these contextsexplicitly in order to give yourself maximum control over formulas.

What is an input context?

 A formula’s input context is simply the list of dimensions that the formula takesinto account when calculating its result. Look at the example from earlier in thischapter:

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

Page 19: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 19/94

BusinessObejcts Advanced Query Building Techniques Guide 19

What is extended syntax?

What is an output context?

 A formula’s output context causes it to output a value is if it were placed in thefooter of a block break (or, in SQL terms, the COMPUTE BY clause of an SQLquery). 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 blockthat has no break? In this case, you need to tell BusinessObjects that theformula’s output context is (Year). The block looks like this:

Page 20: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 20/94

20 BusinessObejcts Advanced Query Building Techniques Guide

Understanding Calculation Contexts

Expressed in words, you are telling BusinessObjects to sum revenues by year  and quarter (the input context), then output the smallest of these values thatoccurs in each year (the output context). The formula for the Min by Year columnis 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. Whenspecifying an input context, you place In <dimension list> inside the functionparentheses. When you specify an output context, you place In <dimension_list> outside function parentheses. In the formula given above, the input and outputcontexts are as follows:

EXAMPLE

Specifying an output context with In

You have a block based on the Island Resorts Marketing universe that showscustomers’ Country, Region,City and Revenue; you want to include averagerevenue 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 theRevenue column. Why is this? This is because the block’s default output contextis (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 thefigure 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>))

Input context Output context

Page 21: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 21/94

BusinessObejcts Advanced Query Building Techniques Guide 21

What is extended syntax?

This gives the following block:

You can see where the figures in the Average column come from by creatinganother block with a break on Country and Region and an average calculation inthe 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 thoseaverages by ignoring the City dimension.

Even such a simple example illustrates the power of calculation contexts. Simplyto create the block BusinessObjects has resolved a complex series of joins andbuilt 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

Page 22: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 22/94

22 BusinessObejcts Advanced Query Building Techniques Guide

Understanding Calculation Contexts

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 usea 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 youwant to add the maximum revenue for each Country/Region combination. Theformula for the Max column in the block is

Page 23: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 23/94

BusinessObejcts Advanced Query Building Techniques Guide 23

What is extended syntax?

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

You are unlikely to want to add columns to blocks as shown in the previousexamples, but these examples show how you can use BusinessObjects to

calculate at numerous different levels of aggregation within the same report byusing context operators. One way you might use this is in an alerter.

Page 24: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 24/94

24 BusinessObejcts Advanced Query Building Techniques Guide

Understanding Calculation Contexts

EXAMPLE

Using context operators and variables to create an aleter 

In this example you have a block showing customers’ country, region, city andrevenues, and you want to show these rows in red where the maximum revenueby 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:

Page 25: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 25/94

BusinessObejcts Advanced Query Building Techniques Guide 25

What is extended syntax?

If you apply this alerter to each column, you can change the format of the columnbased 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 simultaneouslythat gives context operators their power.

EXAMPLESpecifying and input and an output context with In

Formulas can contain both input and output contexts. In this example you havea block based on the eFashion universe and containing Year, Quarter, Month andSales Revenue. You add an additional column with the formula

 Average(<Sales revenue> In (<Year> ,<Quarter>)) In <Year>

Page 26: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 26/94

26 BusinessObejcts Advanced Query Building Techniques Guide

Understanding Calculation Contexts

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

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

Page 27: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 27/94

BusinessObejcts Advanced Query Building Techniques Guide 27

What is extended syntax?

number that appears in the Quarterly Aggregate Average column above.

Remember that the output context is (<Year>), and the output context tellsBusinessObjects 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 BusinessObjectsaverages the aggregate quarterly totals over the year.

The ForEach context operator 

The ForEach operator tells BusinessObjects to add dimension(s) onto the defaultcalculation 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 

Page 28: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 28/94

28 BusinessObejcts Advanced Query Building Techniques Guide

Understanding Calculation Contexts

each year, but without including the Quarter dimension in the block. The formulais Min(<Sales revenue> ForEach <Quarter>). A column with this formula givesthe 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 Mincalculation:

The ForAll context operator 

The ForAll context operator tells BusinessObjects to remove dimensions from thedefault calculation context.

EXAMPLE

Removing a dimension from the input context with ForAll

In this example, based on the eFashion universe, you have a block showingYear, 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

Page 29: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 29/94

BusinessObejcts Advanced Query Building Techniques Guide 29

What is extended syntax?

Sum(<Sales Revenue> ForAll (<Month Name>)). In this situation, ForAll (<Month

Name>) tells BusinessObjects to remove the Month Name dimension from thedefault 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 dimensionsin a calculation. If you have ten dimensions and you wish to calculate across nineof them, it is much simpler to remove the last dimension with ForAll than it is tospecify the whole list explicitly.

Page 30: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 30/94

30 BusinessObejcts Advanced Query Building Techniques Guide

Understanding Calculation Contexts

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 reportsReports change over time, and it is unlikely that a report will contain the same setof dimensions throughout its entire life-cycle. This can cause problems in reportsthat use extended syntax with explicitly-specified lists of dimensions.

Simplification of formulas

Formulas written with extended syntax keywords, especially formulas thatcontain many dimensions, are much easier to read and write when they usekeywords.

List of keywords

The following table lists the extended syntax keywords and the data to which theyrefer:

Keyword Can be used... Refers to...

Body Inside a block The dimensions in theblock

Outside a block The dimensions in thesection

Block Inside a block All dimensions in thesection

Report  Anywhere All dimensions in the

reportCurrentPage  Anywhere The dimensions on the

current page

Page 31: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 31/94

BusinessObejcts Advanced Query Building Techniques Guide 31

Extended syntax keywords

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 quarter’s sales revenue asa 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 thereport by the revenue in the row, thus giving each revenue as a percentage of thetotal.

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 calculationcontext. By removing the Year and Quarter dimensions (the only dimensions inthe report) you tell BusinessObjects to calculate a grand total for the whole report.

Page 32: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 32/94

32 BusinessObejcts Advanced Query Building Techniques Guide

Understanding Calculation Contexts

When you add the Month Name dimension to the block, however, the percentagetotals 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 allrevenues. But when the block contains Month Name, ForAll (<Year>,<Quarter>)removes Year and Quarter from the context, but leaves Month Name. The inputcontext in the divisor therefore becomes Month Name, and the divisor, like thenumerator (which by default returns the total for the row), returns the total for themonth, 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 correctresults. In complex reports with many dimensions this can be difficult to verify. Totest 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 inthe break footer.

This chapter applies these rules in several examples to verify the figures returnedby formulas. See for example Adding a dimension to the input context withForEach on page 27.

Page 33: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 33/94

BusinessObejcts Advanced Query Building Techniques Guide 33

Extended syntax keywords

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-the-scenes 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 totalrevenue for the Bavaria region is 783,520. Hence the rows showing cities inBavaria are highlighted.

The report has a variable, AverageByRegion, with the formula Average(Sum(<Revenue> ForAll(<City>))) In Report , which calculates theaverage of the summed regional revenues. This variable removes City from the

input context of the Sum function, so revenues are summed by country andregion. These sums are averaged, and the Report keyword is placed in the outputcontext of the Average function so that the ‘break’ occurs at the level of the wholereport and the average returned is that of all the sums by region. The reportcontains another variable, SumByRegion, which calculates regional sums. Thisvariable has the formula Sum(<Revenue> ForAll(<City>)).

Page 34: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 34/94

34 BusinessObejcts Advanced Query Building Techniques Guide

Understanding Calculation Contexts

NOTE

You could reference the SumByRegion variable in the AverageByRegionvariable 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 newreport with a block showing Country, Region, City and Revenue. You know thatthe input context of the Sum function specifes the Country and Regiondimensions, so create a section break on (Country, Region); now place a Sumcalculation in the footer of each block. The input context for this Sum calculationis therefore (Country, Region); these sums are the sums returned by theSumByCity 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 youplace the formula Average<Revenue> at the very bottom of the report, outsidethe sections, it returns the average of all the summed revenues, which gives365,169. You can verify this figure against the summed revenues in each sectionand see that, for example, the revenue for West Japan (whose rows are nothighlighted) is smaller, while the revenue for US South (whose rows arehighlighted) is greater.

Page 35: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 35/94

   c     h

   a   p    t   e

   r

Subqueries in BusinessObjects

Page 36: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 36/94

36 BusinessObjects Advanced Query Building Techniques Guide

Subqueries in BusinessObjects

Overview

Subqueries are a powerful SQL feature that allows you to aggregate data atdifferent levels within the same query. BusinessObjects allows you to work withsubqueries 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-levelthen aggregating it in BusinessObjects using extended calculation syntax. (SeeUnderstanding Calculation Contexts on page 15.) What makes subqueriesdifferent is the fact that you filter data on the database server rather than inBusinessObjects. Therefore, if the amount of data your reports are retreivingfrom 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 theaggregation work over to the server, and to reduce the amount of data passedacross the network.

Page 37: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 37/94

BusinessObjects Advanced Query Building Techniques Guide 37

Using subqueries in the Query Panel

Using subqueries in the Query Panel

The simplest way to use a subquery is to select the Subquery operand type whenbuilding 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 youwant the report to return only those countries whose total revenue is greater than$1,000,000. You could do this using extended calculation syntax (UnderstandingCalculation Contexts on page 15) by creating an additional variable to calculaterevenue by country, then filtering on this variable. The variable would have theformula Sum(<Revenue> In <Country>).

In this approach BusinessObjects retrieves the data for all countries then filtersat the client end. This is the appropriate approach if you also want to work withthe data at lower levels of aggregation in the same report. If you do not, youshould use a subquery. When you use a subquery, BusinessObjects generatesSQL that filters the data at the database end before returning it to the client. Tobuild 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 queryRevenue > 1000000

Run the query to return the query result.

38 B i Obj t Ad d Q B ildi T h i G id

Page 38: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 38/94

38 BusinessObjects Advanced Query Building Techniques Guide

Subqueries in BusinessObjects

Comparing subqueries and extended calculation syntax

You can see the differences in the two approaches in the previous example byexamining 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 toBusinessObjects.

BusinessObjects Advanced Query Building Techniques Guide 39

Page 39: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 39/94

BusinessObjects Advanced Query Building Techniques Guide 39

Using subqueries in the Query Panel

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.countryFROM

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) >= 1000000

)

)

)GROUP BY

Resort_Country.country,

Resort.resort

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

40 BusinessObjects Advanced Query Building Techniques Guide

Page 40: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 40/94

40 BusinessObjects Advanced Query Building Techniques Guide

Subqueries in BusinessObjects

Dimension restrictions in subqueries

Comparing dimensions

In the previous example you compared the result of the subquery against theCountry dimension. Note that if you attempt to drag more than one dimension tothe Results Obejcts pane in the subquery tab, the Run button is disabled becausethe subquery can compare one dimension only. Note also that, although you candrag any dimension object to the Result Objects pane, the only object that makessense 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 willnever return any data.

BusinessObjects Advanced Query Building Techniques Guide 41

Page 41: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 41/94

BusinessObjects Advanced Query Building Techniques Guide 41

Creating subqueries by using complex conditions

Creating subqueries by using complexconditions

 Another way of building subqueries is by using complex conditions when youbuild your query in the Query Panel. Calculations are particularly powerful whenused in conjunction with user objects. You can build a user object with anaggregate function, then determine in the calculation at which level the aggregate

is to be calculated. A calculation consists of four componenents, each of which isdefined 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.

EXAMPLEReturn country, resort and revenue for those countries/resorts with higher thanaverage revenue

This report should return the following data because the average revenue bycountry 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 theRevenue 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

42 BusinessObjects Advanced Query Building Techniques Guide

Page 42: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 42/94

j y g q

Subqueries in BusinessObjects

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.

BusinessObjects Advanced Query Building Techniques Guide 43

Page 43: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 43/94

Creating subqueries by using complex conditions

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 todetermine which (if any) dimensions in the subquery are correlated withdimensions in the main query.

9. Select Independently of all your objects. In this case you wish to calculate anoverall average revenue, so the subquery should not be correlated.

10.Click Next.

The Select the Number of Values to Compare screen appears. You use thisscreen to determine how the values returned by the subquery are comparedagainst the main query. In this case the subquery returns one value only, soyou can select either option.

11.Click Finish and run the report.

44 BusinessObjects Advanced Query Building Techniques Guide

Page 44: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 44/94

Subqueries in BusinessObjects

Page 45: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 45/94

   c     h

   a   p    t   e

   r

Working with Prompts

46 BusinessObjects Advanced Query Building Techniques Guide

Page 46: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 46/94

Working with Prompts

Overview

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

BusinessObjects Advanced Query Building Techniques Guide 47

Page 47: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 47/94

Creating meaningful LOVs in prompts

Creating meaningful LOVs in prompts

You can use prompts to supply arguments to functions, but these argumentsare not always meaningful to users. You can map these arguments to moreuser-friendly labels that are displayed in the prompt LOV by using the tech-nique described below.

The following example is based on Microsoft SQL Server and uses Trans-

act-SQL. It also performs revenue calculation specific to the Island ResortsMarketing database. However, the general approach is adaptable to allDBMSs and databases.

NOTE

The BusinessObjects CD contains scripts and instructions for creating theeFashion and Island Resorts Marketing demo databases on SQL Server andOracle.

Creating a Revenue by Day object

This example uses the Island Resorts Marketing Universe against a SQLServer database. You want to create an object that will show total revenueaccrued on different days of the week. You can isolate different days using

the Transact-SQL DATEPART function. For example, if the day in theinvoice_date column of the SALES table is a Tuesday,

DATEPART (dw, sales.invoice_date) returns 3. In order to sum allinvoices 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 sum-ming revenue, you must give them the opportunity to supply the day number 

to the DATEPART function via a prompt. But from the user’s point of view, alist of numbers from 1 to 7 in a prompt LOV is not meaningful. You need toreplace the numbers with the names of the days, then map these names tothe 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 con-verts these names to the numbers required by the function, do two things:

48 BusinessObjects Advanced Query Building Techniques Guide

Page 48: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 48/94

Working with Prompts

1. Create a lookup table in the database that maps the day numbers to theday names.

2. Create a Revenue By Day object that prompts for day names thentransforms these names to numbers using the lookup table.

Creating the lookup table

Your lookup table must contain two columns: one that contains the valuesinput 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 isas follows:

day_num day_name

1 Sunday

2 Monday

3 Tuesday

4 Wednesday

5 Thursday

6 Friday

7 Saturday

BusinessObjects Advanced Query Building Techniques Guide 49

Page 49: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 49/94

Creating meaningful LOVs in prompts

Creating the object

You can now create the Revenue By Day object that uses this table. Thisobject’s 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 daynamewhere day_name in @Prompt('Choose a Day or Days' ,'a'

,{'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Sa

turday'},multi,constrained))

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

50 BusinessObjects Advanced Query Building Techniques Guide

Page 50: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 50/94

Working with Prompts

Revenue By Day objects onto the report. When you run the report, you arepresented 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 * Ser-

vice.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

BusinessObjects Advanced Query Building Techniques Guide 51

Page 51: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 51/94

Creating meaningful LOVs in prompts

The object WHERE clause

The WHERE clause of the Revenue By Day object transforms the user’sselection(s) in the prompt LOV into the numbers required by the DATEPARTfunction. It does this by selecting the value(s) from the day_num column inthe DAYNAME table for the rows where the values in the day_name columnmatch the LOV selections.

52 BusinessObjects Advanced Query Building Techniques Guide

Page 52: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 52/94

Working with Prompts

Creating an ALL option in a prompt

Prompts allow users to select multiple options from a list. For example, a promptmight ask the user to select a country or countries. If the user wants to return datafor all countries, they need to select every item in the list. This is feasible for ashort list of values, but becomes impractical when the list of values grows. It ismuch more elegant to have an ALL option as a shorthand for “every item in thelist 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 itemin 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 valuesIn 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 onerow. (This dummy table is also used in advanced SQL generation; see Creatinga “dummy” table on page 86.) The names of the table and column and thedatatype 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.

BusinessObjects Advanced Query Building Techniques Guide 53

Page 53: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 53/94

Creating an ALL option in a prompt

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 valuesreturned by the Country of origin object itself, so the definition shows theobject 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 additionalquery 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 

Page 54: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 54/94

BusinessObjects Advanced Query Building Techniques Guide 55

Page 55: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 55/94

Creating an ALL option in a prompt

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 theappropriate 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 thenthe 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 @Variablefunction. 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’)

56 BusinessObjects Advanced Query Building Techniques Guide

Page 56: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 56/94

Working with Prompts

Page 57: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 57/94

58 BusinessObjects Advanced Query Building Techniques Guide

Page 58: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 58/94

Building Date-Related Queries

Overview

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

BusinessObjects Advanced Query Building Techniques Guide 59

Page 59: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 59/94

 A technique for date-related queries

A technique for date-related queries

To use this technique, you add a table to your database that lists all possibledates within the periods covered by your reports. In the following examples thistable is called dateset. The dateset table has one column, day_date., plusseveral other columns that split out the component parts of the date. (For example the year or the year + month concatenated into a string.) You canpopulate 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 datetime,

day_date_year integer,

day_date_month 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))

60 BusinessObjects Advanced Query Building Techniques Guide

Page 60: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 60/94

Building Date-Related Queries

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 BusinessObjectsreports in the dateset table.

BusinessObjects Advanced Query Building Techniques Guide 61

Page 61: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 61/94

 A technique for date-related queries

Using the dates tableThe dates table is extremely powerful, and you can use SQL to answer manydate-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 dateset

where day_date_dayofweek = 5

group by day_date_year,

day_date_month

62 BusinessObjects Advanced Query Building Techniques Guide

Page 62: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 62/94

Building Date-Related Queries

EXAMPLE

Return all dates in all months that begin with a Thursday

In this SQL takes advantage of the year_month column, which concatenatesthe year and month of the date into a string. The subquery returns the year/monthstrings of those months that begin with a Thursday. The outer query returns alldates in those years/months:

select day_date

from dateset

where day_date_yearmonth in (

select day_date_yearmonth

from dateset

where day_date_dayofweek = 5

and 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 dateset

where datepart (year, day_date) = 2000

group by datepart (year, day_date),

datepart (month, 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-handSQL data provider, then linking this data provider with other queries. To makeyour date handling more BusinessObjects-specific, you can create date-relatedobjects in the universe and then use these objects in your queries.

BusinessObjects Advanced Query Building Techniques Guide 63

Page 63: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 63/94

 A technique for date-related queries

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, butinclude 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 thenuse this object in a subquery.

To build the object:

1. Select dateset.day_date in the Select box of the Edit Properties Of dialogbox. (This SELECT statement is identical for all date objects; it is the WHEREclause 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

64 BusinessObjects Advanced Query Building Techniques Guide

Page 64: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 64/94

Building Date-Related Queries

d3.day_date_year = d2.day_date_yearand d3.day_date_month = d2.day_date_month))

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

BusinessObjects Advanced Query Building Techniques Guide 65

Page 65: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 65/94

 A technique for date-related queries

You use this prompt to select the last day(s) and the years. When you clickValues 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 endwith the day(s) you selected and that occur in the month(s) you selected.

66 BusinessObjects Advanced Query Building Techniques Guide

Page 66: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 66/94

Building Date-Related Queries

Let’s take a close look at the object WHERE clause, which uses nested subqueriesto do the work. The prompt in the first subquery uses a lookup table that returnsthe names of the days of the week. (This technique is described in more detail inthe 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 tocompare it against the day_date_dayofweek column, which contains the daynumber. There is a further subquery to find the last day of the month [selectmax(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 thereport, then place create a subquery condition on the Invoice Date object. If yourestrict the values of Invoice Day to those days returned by Months beginningwith ?, the report shows only those revenues generated in months ending withthe 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 specifySELECT min (day_date_day) in the second subquery in the Where clauseto 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','Friday','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))

.

BusinessObjects Advanced Query Building Techniques Guide 67

Page 67: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 67/94

 A technique for date-related queries

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 inwhich, for example, Tuesday occurred four times. In this instance you create anobject, Day X occurs Y times. As always, the object Select clause is simply theday_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 theday name. The other prompt allows the user to select the number of occurencesof the day. When the user runs the query, they see the following dialog box:

The SQL filters on the user’s choice of day as described in the previousexamples. To filter on the number of occurrences, the second prompt is matchedagainst the output of the HAVING clause. Stripped of BusinessObjects promptsyntax, the SQL reads as follows:

SELECT day_dateFROM dateset

WHERE day_date_yearmonth IN(

SELECT day_date_yearmonth

FROM dateset d2

WHERE d2.day_date_dayofweek = [user_choice]

68 BusinessObjects Advanced Query Building Techniques Guide

Page 68: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 68/94

Building Date-Related Queries

GROUP BY day_date_yearmonthHAVING COUNT (*) = [user_choice])

Accounting for holiday days

 As well as working with days of the week, you might also be interested inanalyzing the impact of public holidays. You can do this by adding aholiday_flag column to the table, which is set to 0 (when the day is not apublic 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 = 1GROUP BY d2.day_date_yearmonth

HAVING COUNT (holiday_flag) > 0

Once again, you can adapt this SQL to a Designer object, as the followingexample 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 dateset

where 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 allowsthem to restrict the dates returned to those falling in months where a certainnumber of public holidays occur.

BusinessObjects Advanced Query Building Techniques Guide 69

Page 69: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 69/94

 A technique for date-related queries

70 BusinessObjects Advanced Query Building Techniques Guide

Page 70: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 70/94

Building Date-Related Queries

Page 71: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 71/94

   c     h

   a   p    t   e

   r

Working with Hierarchies

72 BusinessObjects Advanced Query Building Techniques Guide

O i

Page 72: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 72/94

Working with Hierarchies

Overview

Relational databases often model hierarchies. This chapter describes sometechniques for working with hierarchies in BusinessObjects.

BusinessObjects Advanced Query Building Techniques Guide 73

Hierarchies in relational databases

Page 73: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 73/94

Hierarchies in relational databases

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

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

74 BusinessObjects Advanced Query Building Techniques Guide

Building a hierarchy result set

Page 74: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 74/94

Working with Hierarchies

Building a hierarchy result setYou can build a hierarchy result set against the Island Resorts Marketingdatabase by creating a free-hand SQL data provider based on the following SQLquery:

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

Let’s examine this query in detail. It returns five columns: hierarchy_country,hierarchy_region, hierarchy_city, item_level and order_col. Thehierarchy_ columns return the names of the countries, regions and cities in thehierarchy, 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 item’s level in the hierarchy (country at level 0, region at 1 andcity at 2). The order_pos column returns a concatenation of all the hierarchyitems: for example “Australia” for Australia, “AustraliaQueensland” for Queensland and “AustraliaQueenslandBrisbane” for Brisbane. You will use thiscolumn to sort the result set. In general, this approach - creating a hierarchyresult set through a set of UNIONed SQL queries - is useful to “flatten” any multi-table hierarchy into a single “table”.

BusinessObjects Advanced Query Building Techniques Guide 75

Displaying the hierarchy in BusinessObjects

Page 75: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 75/94

Hierarchies in relational databases

sp ay g t e e a c y us essObjectsYou can use this result set to display an attractively-formatted hierarchy inBusinessObjects. 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 thehierarchy items in their correct order, Next, create an object that will show theitems with the classic indentation structure that is often used to display

hierarchies (for example in Windows Explorer) and place it in the block. Theformula for this object, item_indented, makes use of the item_level columnto 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>

76 BusinessObjects Advanced Query Building Techniques Guide

The result is as follows:

Page 76: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 76/94

Working with Hierarchies

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

BusinessObjects Advanced Query Building Techniques Guide 77

This alerter produces the following display:

Page 77: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 77/94

Hierarchies in relational databases

+

Adding measures to the hierarchy

So far you have created a formatted hierarchy display, which could be useful inits own right, but which is more likely to have measures associated with it. Howcan you add a revenue measure to the display so that it will calculate the revenueat the correct aggregation level, depending on the row? (For example, totalrevenue 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 dataprovider is based on the Island Resorts Marketing universe and contains thesame dimensions that appear in the hierarchy (Country of origin, Region andCity) as well as the Revenue measure object.

78 BusinessObjects Advanced Query Building Techniques Guide

Now you need to link the dimensions in this second data provider (calledRevenue) to the equivalent dimensions in the first data provider (called

Page 78: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 78/94

Working with Hierarchies

Hierarchy) as follows:

The final step is to create a variable, hierarchy_revenue, that calculates therevenue 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 inthe hierarchy (by checking the value of the item_level variable). It then usesextended calculation syntax to aggregate the revenue at the appropriate level, asshown in the following table. (For more information about extended calculationsyntax see Understanding Calculation Contexts on page 15.)

By using extended calculation syntax, you ensure that you need retrieve therevenue from the database once only, at the lowest level of detail. Subsequentlyyou aggregate the revenue at different levels in BusinessObjects.

Dimension in “Hierarchy” dataprovider 

Linked dimension in “Revenue”data provider 

hierarchy_country Country of origin

hierarchy_region Region

hierarchy_city City

Level Calculation input context

Country hierarchy_country

Region hierarchy_country,hierarchy_region

City hierarchy_country,hierarchy_region,

hierarchy_city

BusinessObjects Advanced Query Building Techniques Guide 79

When you add the hierarchy_revenue variable to the report it appears asfollows:

Page 79: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 79/94

Hierarchies in relational databases

Note that BusinessObjects automatically takes care of the “outer join” that occursbetween the two data providers. BusinessObjects still returns the entirehierarchy, even for those countries, regions and cities that do not haveassociated revenue. It is often better to simulate an outer join by linking dataproviders at the BusinessObjects level rather than defining outer joins in theuniverse at the Designer level, because outer joins add additional designconstraints to the universe.

80 BusinessObjects Advanced Query Building Techniques Guide

Reporting at different levels of the hierarchyOne of the advantages of this kind of hierarchical display is the ability to report

Page 80: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 80/94

Working with Hierarchies

g p y y pon several levels of the hierarchy simultaneously. You have already seen howyou can display revenue for countries, regions and cities in the same column bycreating a separate data provider and using extended calculation syntax. Youcan 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 eachrevenue 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 theaverage 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 ThenAverage(<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-averagerevenues:

BusinessObjects Advanced Query Building Techniques Guide 81

The result is as follows:

Page 81: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 81/94

Hierarchies in relational databases

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.

82 BusinessObjects Advanced Query Building Techniques Guide

Page 82: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 82/94

Working with Hierarchies

Page 83: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 83/94

   c     h

   a   p    t   e   r

 Advanced SQL Generation

Page 84: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 84/94

BusinessObjects Advanced Query Building Techniques Guide 85

SQL generation in DesignerWhen you create an object in Designer you work with two dialog boxes to define

Page 85: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 85/94

SQL generation in Designer 

When you create an object in Designer, you work with two dialog boxes to definethe object SQL: The Edit Properties of dialog box and the Tables dialog box. Inthe first of these dialog boxes you enter the SELECT statement in the Select boxand the WHERE clause in the Where box. You use the Tables dialog box todetermine which tables will appear in the FROM clause. For example, the Regionobject 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 dialogbox.

If you add a WHERE that restricts the regions to “West”, the generated SQL lookslike 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 SELECTstatement, the text in the WHERE box appears, enclosed in parentheses, in theWHERE clause, and the selected tables appear in the FROM clause. Becauseyou must always select a table or tables, this means that SQL statementsgenerated by Designer always contain a SELECT and FROM keyword. You cannot

86 BusinessObjects Advanced Query Building Techniques Guide

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

Page 86: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 86/94

 Advanced SQL Generation

Creating a “dummy” table

What if you want to create universe objects that return the values of databaseserver in-built variables? For example, a ServerVersion object that returns thevalue of the SQL Server @@VERSION variable. The select statement that youwould normally use is SELECT @@VERSION. But Designer objects mustreference a table; if they do not you receive the error message “The query doesnot 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. Thetable data is never referenced in your queries; it simply exists to fill out the SQLof queries that do not strictly speaking need to reference a table. If this table iscalled DUMMY and has one column, col, containing one row of data (the datatypeof 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:

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 SQLgenerated by Designer? What if you want to create an object that returns all the

Page 87: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 87/94

SQL generation in Designer 

g y g y jdistinct invoice years in the Island Resorts Marketing database, sorted inascending 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 EditProperties Of dialog box. But the important thing to remember is that the onlyclient-side validation that BusinessObjects performs is to check that you haveselected a table in the Tables dialog box. Apart from that, Designer builds theSQL based on the contects of the Select and Where boxes and sends it to thedatabase for validation. It is the database that determines whether the generatedSQL is valid.

Bearing this in mind, you can force Designer into generating the SQL you arelooking for. The SELECT clause presents no problem: simply type DISTINCT

datepart (year, invoice_date) as invoice_year and Designer prefixesthis with the SELECT keyword. The table list is equally straighforward; simplyselect the sales table from the list.

It is the WHERE clause that presents the difficulty. In fact, this query does notneed 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 bydefault. You need to supply your own WHERE condition that will always besatisfied (1=1) and follow it with a bracket to close the parentheses. Now you canadd the ORDER BY clause. (Note that you can reference the invoice_year alias created in the Select box because Designer sends off the whole generatedSQL to the database for validation.)

Finally you need to deal with the closing bracket that Designer adds around theWHERE clause. (As far as Designer is concerned, everything in the Where boxis the WHERE clause.) You can remove this by prefixing it with a comment mark,--, to cause the database to ignore it.

88 BusinessObjects Advanced Query Building Techniques Guide

Designer generates the following SQL based on the text you typed in the EditProperties Of dialog box:

SELECT

Page 88: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 88/94

 Advanced SQL Generation

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 setswhose 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 thanselect 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 withinan aliased block and treats the columns returned as columns in a derived table.

BusinessObjects Advanced Query Building Techniques Guide 89

EXAMPLE

Using a derived table to build a visual hierarchy

I thi l d i d t bl t b ild th i l hi h th t b ilt

Page 89: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 89/94

SQL generation in Designer 

In this example you use a derived table to build the visual hierarchy that you builtearlier using free-hand SQL (see Working with Hierarchies on page 71.) Thedifference 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 free-hand SQL solution is fine, but if multiple users need the same capability it makessense to migrate it back to the Designer level.) The hierarchy, which displayscustomer locations in the Island Resorts Marketing database, appears as follows::

90 BusinessObjects Advanced Query Building Techniques Guide

The first thing you need to do is to build the SQL that will return a result setshowing all the hierarchy items, their level in the hierarchy, and their sort order.The following SQL does this:

select country as hierarchy country,

Page 90: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 90/94

 Advanced SQL Generation

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

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 thatDesigner uses when building the SQL.

Page 91: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 91/94

SQL generation in Designer 

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

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

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 buildthe derived table with the name of the derived table For example the SQL for

Page 92: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 92/94

 Advanced SQL Generation

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 thesame as you used with free-hand SQL in the chapter Working with Hierarchieson page 71. See that chapter for more detailed explanations of the steps in thefollowing 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 thehierarchy.

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.

Page 93: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 93/94

94 BusinessObjects Advanced Query Building Techniques Guide

Page 94: Business Objects - Advanced

7/30/2019 Business Objects - Advanced

http://slidepdf.com/reader/full/business-objects-advanced 94/94

Index