business objects advanced query building techniques

Upload: vinner786

Post on 11-Oct-2015

26 views

Category:

Documents


0 download

DESCRIPTION

Business Objects

TRANSCRIPT

  • BusinessObjects Advanced Query Building Techniques Guide

    BusinessObjects 6.5

    Windows

  • 2 BusinessObjects Advanced Query Building Techniques Guide

    Copyright Copyright 2004 Business Objects. All rights reserved.If you find any problems with this documentation, please report them to Business Objects in writing at [email protected].

    Trademarks Business Objects, the Business Objects logo, Crystal Reports, and Crystal Enterprise are trademarks or registered trademarks of Business Objects SA or its affiliated companies in the United States and other countries. All other names mentioned herein may be trademarks of their respective owners.

    Use restrictions This software and documentation is commercial computer software under Federal Acquisition regulations, and is provided only under the Restricted Rights of the Federal Acquisition Regulations applicable to commercial computer software provided at private expense. The use, duplication, or disclosure by the U.S. Government is subject to restrictions set forth in subdivision (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at 252.227-7013.

    Patents Business Objects owns the following U.S. patents, which may cover products that are offered and sold by Business Objects: 5,555,403, 6,247,008 B1, 6,578,027 B2, 6,490,593 and 6,289,352.

  • BusinessObjects Advanced Query Building Guide 3

    Contents

    C

    C

    C

    C

    C

    CContentsContents 3

    Examples 5

    Preface Maximizing Your Information Resources 7Information resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Useful addresses at a glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12About this guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    hapter 1 Understanding Calculation Contexts 15Defining the calculation context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17What is extended syntax? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Extended syntax keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

    hapter 2 Subqueries in BusinessObjects 35Using subqueries in the Query Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Creating subqueries by using complex conditions . . . . . . . . . . . . . . . . . . . . 41

    hapter 3 Working with Prompts 45Creating meaningful LOVs in prompts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47Creating an ALL option in a prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

    hapter 4 Building Date-Related Queries 57A technique for date-related queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

    hapter 5 Working with Hierarchies 71Hierarchies in relational databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

    hapter 6 Advanced SQL Generation 83SQL generation in Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

  • 4 BusinessObjects Advanced Query Building Guide

    Contents

    Index 93

  • BusinessObjects Advanced Query Building Guide 5

    DRA

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

  • 6 BusinessObjects Advanced Query Building Guide

    Examples DRAFT

  • eMaximizing Your Information Resourcesprefac

  • 8 BusinessObjects Advanced Query Building Guide

    Maximizing

    OverviewInfo Your Information Resources

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

  • BusinessObjects Advanced Query Building Guide 9

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

    WheInformation resources

    re do I start? Below are a few suggested starting points; there is a summary of useful web addresses on page 12.

    X Documentation RoadmapThe Documentation Roadmap references all Business Objects guides and multimedia, and lets you see at a glance what information is available, from where, and in what format. View or download the Business Objects Documentation Roadmap at www.businessobjects.com/services/documentation.htm

    X Documentation from the productsYou can access electronic documentation at any time from the product you are using. Online help, multimedia, and guides in Adobe PDF format are available from the product Help menus.

    X Documentation on the webThe full electronic documentation set is available to customers with a valid maintenance agreement on the Online Customer Support (OCS) website at www.businessobjects.com/services/support.htm

    X Buy printed documentationYou can order printed documentation through your local sales office, or from the online Business Objects Documentation Supply Store at www.businessobjects.com/services/documentation.htm

    X Search the Documentation CDSearch across the entire documentation set on the Business Objects Documentation CD shipped with our products. This CD brings together the full set of documentation, plus tips, tricks, multimedia tutorials, and demo materials.Order the Documentation CD online, from the Business Objects Documentation Supply Store, or from your local sales office.

  • 10 BusinessObjects Advanced Query Building Guide

    Maximizing

    X MultimediaAre you new to Business Objects? Are you upgrading from a previous release or expanding, for example, from our desktop to our web solution? Try one of our multimedia quick tours or Getting Started tutorials. All are available via the Online

    How

    Sen Your Information Resources

    Customer Support (OCS) website or on the Documentation CD.

    can I get the most recent documentation?You can get our most up-to-date documentation via the web. Regularly check the sites listed below for the latest documentation, samples, and tips.

    X Tips & TricksOpen to everyone, this is a regularly updated source of creative solutions to any number of business questions. You can even contribute by sending us your own tips.www.businessobjects.com/forms/tipsandtricks_login.asp

    X Product documentationWe regularly update and expand our documentation and multimedia offerings. With a valid maintenance agreement, you can get the latest documentation in seven languages on the Online Customer Support (OCS) website.

    X Developer Suite OnlineDeveloper Suite Online provides documentation, samples, and tips to those customers with a valid maintenance agreement and a Developer Suite license via the Online Customer Support (OCS) website.

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

    NOTEIf 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

  • BusinessObjects Advanced Query Building Guide 11

    ServicesA global network of Business Objects technology experts provides customer support, education, and consulting to ensure maximum business intelligence

    How

    Hav

    Loo

    LooServices

    benefit to your business.

    we can support you?Business Objects offers customer support plans to best suit the size and requirements of your deployment. We operate three global customer support centers: Americas: San Jose, California and Atlanta, Georgia Europe: Maidenhead, United Kingdom Asia: Tokyo, Japan and Sydney, Australia

    X Online Customer SupportOur Customer Support website is open to all direct customers with a current maintenance agreement, and provides the most up-to-date Business Objects product and technical information. You can log, update, and track cases from this site using the Business Objects Knowledge Base.

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

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

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

  • 12 BusinessObjects Advanced Query Building Guide

    Maximizing

    Useful addresses at a glance

    Address ContentBus

    wwwdocu

    Busmai

    docu

    Pro

    wwwsupp

    Bus

    www

    Dev

    www

    Kno

    www

    Tips

    wwwtipsa Your Information Resources

    iness Objects Documentation

    .businessobjects.com/services/mentation.htm

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

    iness Objects Documentation lbox

    [email protected]

    Feedback or questions about documentation.

    duct documentation

    .businessobjects.com/services/ort.htm

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

    iness Objects product information

    .businessobjects.com

    Information about the full range of Business Objects products.

    eloper Suite Online

    .techsupport.businessobjects.com

    Available to customers with a valid maintenance agreement and a Developer Suite license via the Online Customer Support (OCS) website. Provides all the documentation, latest samples, kits and tips.

    wledge Base (KB)

    .techsupport.businessobjects.com

    Technical articles, documents, case resolutions.Also, use the Knowledge Exchange to learn what challenges other users both customers and employees face and what strategies they find to address complex issues. From the Knowledge Base, click the Knowledge Exchange link.

    & Tricks

    .businessobjects.com/forms/ndtricks_login.asp

    Practical business-focused examples.

  • BusinessObjects Advanced Query Building Guide 13

    Online Customer Support

    www

    www

    Bus

    wwweduc

    Bus

    wwwcons

    Address ContentUseful addresses at a glance

    .techsupport.businessobjects.com

    .businessobjects.com/services

    Starting point for answering questions, resolving issues.

    Information about registering with Worldwide Customer Support.

    iness Objects Education Services

    .businessobjects.com/services/ation.htm

    The range of Business Objects training options and modules.

    iness Objects Consulting Services

    .businessobjects.com/services/ulting.htm

    Information on how Business Objects can help maximize your business intelligence investment.

  • 14 BusinessObjects Advanced Query Building Guide

    Maximizing

    About this guideThis guide describes advanced query-building techniques using BusinessObjects and Designer.

    Aud

    Con Your Information Resources

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

    ventions used in this guideThe conventions used in this guide are described in the table below.

    Convention IndicatesSmall capitals The names of all products such as

    BusinessObjects, 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 Objects installation/configuration directory structure. For example: $INSTALLDIR refers to the Business Objects

    installation directory. $LOCDATADIR refers to a subdirectory of the

    BusinessObjects installation directory called locData.

  • rUnderstanding Calculation Contextschapte

  • 16 BusinessObejcts Advanced Query Building Techniques Guide

    Understand

    OverviewExtended calculation syntax is one of BusinessObjects most powerful yet least ing Calculation Contexts

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

  • BusinessObejcts Advanced Query Building Techniques Guide 17

    Defining the calculation contextWhat are calculation contexts?Defining the calculation context

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

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

  • 18 BusinessObejcts Advanced Query Building Techniques Guide

    Understand

    What is extended syntax?Extended syntax allows you to specify calculation contexts explicitly, which means that you do not need to accept BusinessObjects defaults. To use

    Inpuing Calculation Contexts

    extended syntax you need to be familiar with three concepts: input and output contexts context operators extended syntax keywords

    t and output contextsA measure or formulas input and output contexts determine what number the measure or formula returns. You use extended syntax to specify these contexts explicitly in order to give yourself maximum control over formulas.

    X What is an input context?A formulas input context is simply the list of dimensions that the formula takes into account when calculating its result. Look at the example from earlier in this chapter:

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

  • BusinessObejcts Advanced Query Building Techniques Guide 19

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

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

  • 20 BusinessObejcts Advanced Query Building Techniques Guide

    Understand

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

    Exteing Calculation Contexts

    nded syntax context operatorsYou specify a formula context explicitly by including context operators in the formula. There are three context operators: In, ForEach and ForAll.

    X The In context operatorYou use the In operator to specify an explicitly-named list of dimensions. When specifying an input context, you place In inside the function parentheses. When you specify an output context, you place In outside function parentheses. In the formula given above, the input and output contexts are as follows:

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

    Input context Output context

  • BusinessObejcts Advanced Query Building Techniques Guide 21

    This gives the following block:What is extended syntax?

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

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

  • 22 BusinessObejcts Advanced Query Building Techniques Guide

    Understand

    same block. Even if the table structure behind this report were radically simplified, with all dimensions and revenue stored in one table, you would still need to use a correlated subquery to achieve the same result:ing Calculation Contexts

    select country, region, city, revenue,

    (select avg (revenue) from geo g2where g2.country = g1.countryand g2.region = g1.regiongroup by g2.country,g2.region) as sum_by_country_region

    from geo g1

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

  • BusinessObejcts Advanced Query Building Techniques Guide 23

    Max( In ( ,))What is extended syntax?

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

  • 24 BusinessObejcts Advanced Query Building Techniques Guide

    Understand

    EXAMPLEUsing context operators and variables to create an aleterIn this example you have a block showing customers country, region, city and ing Calculation Contexts

    revenues, and you want to show these rows in red where the maximum revenue by country and region is greater then $700,000. To do this, create a variable, MaxCountryRegion, with the formula Max( In ( ,)). You can now use this variable in the definition of an alerter:

  • BusinessObejcts Advanced Query Building Techniques Guide 25

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

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

    EXAMPLESpecifying and input and an output context with InFormulas can contain both input and output contexts. In this example you have a block based on the eFashion universe and containing Year, Quarter, Month and Sales Revenue. You add an additional column with the formulaAverage( In ( ,)) In

  • 26 BusinessObejcts Advanced Query Building Techniques Guide

    Understand

    What is this column showing? This formula tells BusinessObjects to take the average of the aggregated quarterly revenues. The input context, (,) tells BusinessObjects to aggregate revenues into quarterly totals. The output context, () tells BusinessObjects to average these ing Calculation Contexts

    aggregated revenue across each year.

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

  • BusinessObejcts Advanced Query Building Techniques Guide 27

    number that appears in the Quarterly Aggregate Average column above. What is extended syntax?

    Remember that the output context is (), and the output context tells BusinessObjects to output the result as if it appeared in the footer of a break on the dimension(s) specified in the output context. This is why BusinessObjects averages the aggregate quarterly totals over the year.

    X The ForEach context operatorThe ForEach operator tells BusinessObjects to add dimension(s) onto the default calculation context.

    EXAMPLEAdding a dimension to the input context with ForEachIn 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

  • 28 BusinessObejcts Advanced Query Building Techniques Guide

    Understand

    each year, but without including the Quarter dimension in the block. The formula is Min( ForEach ). A column with this formula gives the following results:ing Calculation Contexts

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

    X The ForAll context operatorThe ForAll context operator tells BusinessObjects to remove dimensions from the default calculation context.

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

  • BusinessObejcts Advanced Query Building Techniques Guide 29

    Sum( ForAll ()). In this situation, ForAll () tells BusinessObjects to remove the Month Name dimension from the default input context (Year, Quarter, Month Name), giving the following result:What is extended syntax?

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

  • 30 BusinessObejcts Advanced Query Building Techniques Guide

    Understand

    Extended syntax keywordsExtended syntax keywords allow you to refer to dimensions generically rather than through hard-coded lists. This has two main benefits:

    Futu

    Sim

    Listing Calculation Contexts

    Future-proofing of reports Simplification of formulas

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

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

    of keywordsThe following table lists the extended syntax keywords and the data to which they refer:

    Keyword Can be used... Refers to...Body Inside a block The dimensions in the

    block

    Outside a block The dimensions in the section

    Block Inside a block All dimensions in the section

    Report Anywhere All dimensions in the report

    CurrentPage Anywhere The dimensions on the current page

  • BusinessObejcts Advanced Query Building Techniques Guide 31

    EXAMPLEUsing keywords to avoid incorrect resultsIn this example you have a report showing Year, Quarter and Sales Revenue, Extended syntax keywords

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

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

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

  • 32 BusinessObejcts Advanced Query Building Techniques Guide

    Understand

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

    Tesing Calculation Contexts

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

    ting formulas with extended syntaxIt is important to be sure that formulas that return extended syntax return correct results. In complex reports with many dimensions this can be difficult to verify. To test your figures, keep the following two rules in mind, and use these rules to build test reports.1. The input context determines which dimensions go into the calculation;2. The output context creates a break and aggregates totals as if they were in

    the break footer.This chapter applies these rules in several examples to verify the figures returned by formulas. See for example Adding a dimension to the input context with ForEach on page 27.

  • BusinessObejcts Advanced Query Building Techniques Guide 33

    EXAMPLECreating a test report to verify a formulaThis example shows how calculation contexts can operate at different levels Extended syntax keywords

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

  • 34 BusinessObejcts Advanced Query Building Techniques Guide

    Understand

    NOTEYou could reference the SumByRegion variable in the AverageByRegion variable to simplfy it. In this case its formula becomes ing Calculation Contexts

    Average() In Report

    You use these two variables to create an alerter that highlights the appropriate rows.

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

  • rSubqueries in BusinessObjectschapte

  • 36 BusinessObjects Advanced Query Building Techniques Guide

    Subqueries

    OverviewSubqueries are a powerful SQL feature that allows you to aggregate data at in BusinessObjects

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

  • BusinessObjects Advanced Query Building Techniques Guide 37

    Using subqueries in the Query PanelThe simplest way to use a subquery is to select the Subquery operand type when building a query in the query panel.Using subqueries in the Query Panel

    EXAMPLEShow revenue by country and region where the country revenue > $1,000,000In this example you have a report showing country, region and revenue and you want the report to return only those countries whose total revenue is greater than $1,000,000. You could do this using extended calculation syntax (Understanding Calculation Contexts on page 15) by creating an additional variable to calculate revenue by country, then filtering on this variable. The variable would have the formula Sum( In ). In this approach BusinessObjects retrieves the data for all countries then filters at the client end. This is the appropriate approach if you also want to work with the data at lower levels of aggregation in the same report. If you do not, you should use a subquery. When you use a subquery, BusinessObjects generates SQL that filters the data at the database end before returning it to the client. To build this query using a subquery:1. Drag the Country, Region and Revenue objects to the Result Objects pane of

    the Query Panel.2. Drag the Country object to the Conditions pane (because you want to filter the

    data at source by country).3. Select the Equal To operator.4. Select the Create a Subquery (ANY) operator.

    The subquery appears as an additional tab on the Query Panel.5. In the additional tab, drag the Country object to the Result Objects pane.6. Drag the Revenue object to the Conditions pane and set up the query

    Revenue > 1000000

    Run the query to return the query result.

  • 38 BusinessObjects Advanced Query Building Techniques Guide

    Subqueries

    Comparing subqueries and extended calculation syntaxYou can see the differences in the two approaches in the previous example by examining the SQL generated by the query. When you used extended syntax, BusinessObjects generated the following SQL: in BusinessObjects

    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_LineWHERE ( Resort_Country.country_id=Resort.country_id ) AND ( Invoice_Line.service_id=Service.service_id ) AND ( Resort.resort_id=Service_Line.resort_id ) AND ( Service.sl_id=Service_Line.sl_id )GROUP BY Resort_Country.country, Resort.resort

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

  • BusinessObjects Advanced Query Building Techniques Guide 39

    When you use a subquery, the SQL looks like this:SELECT Resort_Country.country, Resort.resort, sum(Invoice_Line.days * Invoice_Line.nb_guests * Service.price)Using subqueries in the Query Panel

    FROM Country Resort_Country, Resort, Invoice_Line, Service, Service_LineWHERE

    ( 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, ResortWHERE

    ( 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.countryHAVING ( 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 a HAVING clause to the SQL, which means that the condition is applied on the database server and two rows only are returned to the client.

  • 40 BusinessObjects Advanced Query Building Techniques Guide

    Subqueries

    Dimension restrictions in subqueries

    X Comparing dimensionsIn the previous example you compared the result of the subquery against the in BusinessObjects

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

  • BusinessObjects Advanced Query Building Techniques Guide 41

    Creating subqueries by using complex conditionsCreating subqueries by using complex conditions

    Another way of building subqueries is by using complex conditions when you build your query in the Query Panel. Calculations are particularly powerful when used in conjunction with user objects. You can build a user object with an aggregate function, then determine in the calculation at which level the aggregate is to be calculated. A calculation consists of four componenents, each of which is defined by a step in the calculation wizard.1. The dimension or measure used in the calculation2. The grouping dimensions3. The synchronizing dimensions4. The number of values to compare.

    EXAMPLEReturn country, resort and revenue for those countries/resorts with higher than average revenueThis report should return the following data because the average revenue by country and resort is $1,095,508.

    One way to do this is with a calculation. To do this:1. Create a user object, Average Revenue, that calculates the average of the

    Revenue measure.2. Drag the Revenue object to the Conditions pane in the Query panel.3. Select the Greater than or equal to operator.4. Select Calculation.

    The Complex Condition wizard appears at the Select an Object screen.You use the Select an Object screen to determine which dimension or measure is used in the comparison between the main query and the

  • 42 BusinessObjects Advanced Query Building Techniques Guide

    Subqueries

    subquery.5. Select the Average Revenue user object. in BusinessObjects

    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

    This means that the average revenue will be calculated by country and resort.8. Click Next.

    The Synchronize Your Calculation screen appears. You use this dialog box to determine which (if any) dimensions in the subquery are correlated with Creating subqueries by using complex conditions

    dimensions in the main query.9. Select Independently of all your objects. In this case you wish to calculate an

    overall average revenue, so the subquery should not be correlated.

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

    11.Click Finish and run the report.

  • 44 BusinessObjects Advanced Query Building Techniques Guide

    Subqueries in BusinessObjects

  • rWorking with Promptschapte

  • 46 BusinessObjects Advanced Query Building Techniques Guide

    Working wi

    OverviewPrompts allow you to make reports generic by giving the user the option to supply th Prompts

    arguments when they run the report. There are several techniques you can use to enhance the basic prompts provided by BusinessObjects.

  • BusinessObjects Advanced Query Building Techniques Guide 47

    Creating meaningful LOVs in promptsYou can use prompts to supply arguments to functions, but these arguments are not always meaningful to users. You can map these arguments to more

    Crea

    MapCreating meaningful LOVs in prompts

    user-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 Resorts Marketing database. However, the general approach is adaptable to all DBMSs and databases.

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

    ting a Revenue by Day objectThis example uses the Island Resorts Marketing Universe against a SQL Server database. You want to create an object that will show total revenue accrued on different days of the week. You can isolate different days using the Transact-SQL DATEPART function. For example, if the day in the invoice_date column of the SALES table is a Tuesday, DATEPART (dw, sales.invoice_date) returns 3. In order to sum all invoices where the invoice date falls on a Tuesday, you include the condition WHERE DATEPART (dw, invoice_date) = 3 in the query SQL.If you want the report user to be able to isolate particular days when sum-ming revenue, you must give them the opportunity to supply the day number to the DATEPART function via a prompt. But from the users point of view, a list of numbers from 1 to 7 in a prompt LOV is not meaningful. You need to replace the numbers with the names of the days, then map these names to the numbers to be input to the function.

    ping function arguments to labelsTo 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

    Working wi

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

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

    Creath Prompts

    ting the lookup tableYour lookup table must contain two columns: one that contains the values input directly to the function, and another that maps these values to labels. In this case, create a table called DAYNAME with the columns day_num (of type integer) and day_name (of type varchar). The data in this table is as follows:

    day_num day_name1 Sunday

    2 Monday

    3 Tuesday

    4 Wednesday

    5 Thursday

    6 Friday

    7 Saturday

  • BusinessObjects Advanced Query Building Techniques Guide 49

    Creating the objectYou can now create the Revenue By Day object that uses this table. This objects Select is defined as SUM(Invoice_line.days * Invoice_Line.nb_guests *

    RunCreating meaningful LOVs in prompts

    Service.price) and its Where is defined as:DATEPART (dw, Sales.invoice_date) in (select daynum from dayname where day_name in @Prompt('Choose a Day or Days' ,'a' ,{'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'},multi,constrained))

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

  • 50 BusinessObjects Advanced Query Building Techniques Guide

    Working wi

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

    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

    The object WHERE clauseThe WHERE clause of the Revenue By Day object transforms the users selection(s) in the prompt LOV into the numbers required by the DATEPART function. It does this by selecting the value(s) from the day_num column in Creating meaningful LOVs in prompts

    the DAYNAME table for the rows where the values in the day_name column match the LOV selections.

  • 52 BusinessObjects Advanced Query Building Techniques Guide

    Working wi

    Creating an ALL option in a promptPrompts allow users to select multiple options from a list. For example, a prompt might ask the user to select a country or countries. If the user wants to return data

    Addth Prompts

    for all countries, they need to select every item in the list. This is feasible for a short list of values, but becomes impractical when the list of values grows. It is much more elegant to have an ALL option as a shorthand for every item in the list of values.This section shows how you can add an ALL option to a prompt. When the user selects ALL, BusinessObjects returns data as if the user had selected every item in the list of values.This technique has two steps:1. Add ALL to an object list of values2. Create a prompt using SQL CASE logic

    ing 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 one row. (This dummy table is also used in advanced SQL generation; see Creating a dummy table on page 86.) The names of the table and column and the datatype of the one row of data are irrelevant. In this example, the table is called dummy, the column is col and it is populated with one integer.

  • BusinessObjects Advanced Query Building Techniques Guide 53

    To add ALL to the Country of origin list of values, you modify the list of values definition in Designer. By default the list of values is simply the values returned by the Country of origin object itself, so the definition shows the object in the Result Objects pane of the Query Panel. To add ALL:Creating an ALL option in a prompt

    1. Create an additional object called ALL. This object simply selects the col column from the dummy table.

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

  • 54 BusinessObjects Advanced Query Building Techniques Guide

    Working wi

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

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

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

  • BusinessObjects Advanced Query Building Techniques Guide 55

    In full, the WHERE clause is as follows:country in (select case @Prompt('Choose a country or countries','a','Customer\Country of origin',multi,constrained) when 'ALL' then country else Creating an ALL option in a prompt

    @Variable('Choose a country or countries') end)This SQL uses the CASE construction to test the user input and perform the appropriate processing. The prompt list of values is the Country of origin list of values (which now contains the ALL option.) If the user selects ALL then the subquery simply returns all countries in the list of countries (when ALL then country). If the user selects a country or countries, on the other hand, the subquery returns the list of countries they selected through the @Variable function. The ALL SQL is therefore:SELECT country

    FROM country

    WHERE country in (SELECT country from country)If the user selects the US and Holland, the SQL is:SELECT country

    FROM country

    WHERE country IN (US, Holland)

  • 56 BusinessObjects Advanced Query Building Techniques Guide

    Working with Prompts

  • rBuilding Date-Related Querieschapte

  • 58 BusinessObjects Advanced Query Building Techniques Guide

    Building Da

    OverviewDates are a major component of any BusinessObjects report. This chapter shows te-Related Queries

    a technique that allows you to answer sophisticated date-related questions. The technique involves adding a database table to your database. You then add universe objects that reference this table.

  • BusinessObjects Advanced Query Building Techniques Guide 59

    A technique for date-related queriesTo use this technique, you add a table to your database that lists all possible dates within the periods covered by your reports. In the following examples this A technique for date-related queries

    table is called dateset. The dateset table has one column, day_date., plus several other columns that split out the component parts of the date. (For example the year or the year + month concatenated into a string.) You can populate this table using a simple stored procedure, as follows:

    create procedure sp_pop_dateset ( @start_date datetime ,@end_date datetime ) as

    begin

    create table dateset ( day_date 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

  • 60 BusinessObjects Advanced Query Building Techniques Guide

    Building Da

    when 1 then 0 + convert (char(1), month(@date)) else convert (char(2), month(@date)) endte-Related Queries

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

    end

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

  • BusinessObjects Advanced Query Building Techniques Guide 61

    Using the dates tableThe dates table is extremely powerful, and you can use SQL to answer many date-related questions, as the following examples show.A technique for date-related queries

    EXAMPLEReturn all leap yearsThe 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

    EXAMPLEHow 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

    Building Da

    EXAMPLEReturn all dates in all months that begin with a ThursdayIn this SQL takes advantage of the year_month column, which concatenates

    Create-Related Queries

    the year and month of the date into a string. The subquery returns the year/month strings of those months that begin with a Thursday. The outer query returns all dates in those years/months:select day_date

    from dateset

    where day_date_yearmonth in (select day_date_yearmonth

    from dateset

    where day_date_dayofweek = 5

    and day_date_day = 1 )

    EXAMPLEReturn the last day of each month in the year 2000This query also uses aggregation and grouping:select max (day_date)from dateset

    where datepart (year, day_date) = 2000group by datepart (year, day_date), datepart (month, day_date)

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

  • BusinessObjects Advanced Query Building Techniques Guide 63

    EXAMPLEShow revenue and include only those months that end on a particular day or days in the calculationA technique for date-related queries

    In this example you will build a report showing country, region and revenue, but include only those invoices that occurred in a month that ends on a particular day(s) (selected by the user) and in a particular year (also selected by the user).To build this query you need an object (in this example called Months beginning with ?) that returns all dates that end with the day. You will then use this object in a subquery.To build the object:1. Select dateset.day_date in the Select box of the Edit Properties Of dialog

    box. (This SELECT statement is identical for all date objects; it is the WHERE clause is the place where the real interest occurs.)

    2. Type the following SQL in the Where clause of the Edit Properties Of dialog box:day_date_year in @Prompt('Choose a year or years' ,'n' ,'DateObjects\CountryPrompt',multi,constrained)and day_date_yearmonth in (select day_date_yearmonth from dateset d2 where day_date_dayofweek in (select day_num from dayname where day_name in @Prompt('Choose a last day(s)' ,'a' ,{'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'},multi,constrained)) and day_date_day = ( select max (day_date_day) from dateset d3 where

  • 64 BusinessObjects Advanced Query Building Techniques Guide

    Building Da

    d3.day_date_year = d2.day_date_yearand d3.day_date_month = d2.day_date_month))te-Related Queries

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

  • BusinessObjects Advanced Query Building Techniques Guide 65

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

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

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

  • 66 BusinessObjects Advanced Query Building Techniques Guide

    Building Da

    Lets take a close look at the object WHERE clause, which uses nested subqueries to do the work. The prompt in the first subquery uses a lookup table that returns the names of the days of the week. (This technique is described in more detail in the section Creating meaningful LOVs in prompts on page 47.) in the chapter te-Related Queries

    Working with Prompts.) The lookup table maps the day name to its number to compare it against the day_date_dayofweek column, which contains the day number. There is a further subquery to find the last day of the month [select max(day_date_day)...] The result of these two subqueries is that the list of dates whose day_date_yearmonth column corresponds to the year/month of the months whose last day falls on the day chosen by the user.You can now use the list of dates returned by the Months beginning with ? object in a subquery. Place the Country, Region and Revenue objects in the report, then place create a subquery condition on the Invoice Date object. If you restrict the values of Invoice Day to those days returned by Months beginning with ?, the report shows only those revenues generated in months ending with the day(s) you specified.

    EXAMPLEShow revenue and include only those months that begin on a particular day or days in the calculationThis example is almost identical to the previous example, except that you specify SELECT min (day_date_day) in the second subquery in the Where clause to return the first day of the month rather than the last. The Where clause SQL is as follows:day_date_year in @Prompt('Choose a year or years' ,'n' ,'DateObjects\CountryPrompt',multi,constrained)and day_date_yearmonth in (select day_date_yearmonth from dateset d2 where day_date_dayofweek in (select day_num from dayname where day_name in @Prompt('Choose a last day(s)' ,'a'

    ,{'Sunday','Monday','Tuesday','Wednesday','Thursday','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

    EXAMPLEShow revenue and include only those months that contain X occurrences of day YA technique for date-related queries

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

    The SQL filters on the users choice of day as described in the previous examples. To filter on the number of occurrences, the second prompt is matched against the output of the HAVING clause. Stripped of BusinessObjects prompt syntax, the SQL reads as follows:SELECT day_date

    FROM dateset

    WHERE day_date_yearmonth IN(SELECT day_date_yearmonth

    FROM dateset d2

    WHERE d2.day_date_dayofweek = [user_choice]

  • 68 BusinessObjects Advanced Query Building Techniques Guide

    Building Da

    GROUP BY day_date_yearmonth

    HAVING COUNT (*) = [user_choice])

    Accounting for holiday dayste-Related Queries

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

    EXAMPLEReturn all dates in months that have X public holidaysTo 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_yearmonthfrom 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 allows them to restrict the dates returned to those falling in months where a certain number of public holidays occur.

  • BusinessObjects Advanced Query Building Techniques Guide 69A technique for date-related queries

  • 70 BusinessObjects Advanced Query Building Techniques Guide

    Building Date-Related Queries

  • rWorking with Hierarchieschapte

  • 72 BusinessObjects Advanced Query Building Techniques Guide

    Working wi

    OverviewRelational databases often model hierarchies. This chapter describes some th Hierarchies

    techniques for working with hierarchies in BusinessObjects.

  • BusinessObjects Advanced Query Building Techniques Guide 73

    Hierarchies in relational databasesHierarchies in relational databases are usually modelled as a series of parent and child tables, with each child connected to its parent by a foreign key. For Hierarchies in relational databases

    example, in the Island Resorts Marketing database, the Country, Region and City tables model a geographical hierarchy:

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

  • 74 BusinessObjects Advanced Query Building Techniques Guide

    Working wi

    Building a hierarchy result setYou can build a hierarchy result set against the Island Resorts Marketing database by creating a free-hand SQL data provider based on the following SQL query:th Hierarchies

    select country as hierarchy_country, NULL as hierarchy_region, NULL as hierarchy_city, 0 as item_level, country as order_colfrom countryunionselect c.country as hierarchy_country, region as hierarchy_region, NULL as hierarchy_city, 1 as item_level, c.country + r.region as order_colfrom region r, country cwhere c.country_id = r.country_idunionselect 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_colfrom city c, region r, country c2where r.region_id = c.region_idand r.country_id = c2.country_id

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

  • BusinessObjects Advanced Query Building Techniques Guide 75

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

    How can you turn this into a formatted hierarchical display? The following example shows the process.

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

  • 76 BusinessObjects Advanced Query Building Techniques Guide

    Working wi

    The result is as follows:th Hierarchies

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

  • BusinessObjects Advanced Query Building Techniques Guide 77

    This alerter produces the following display:

    AddHierarchies in relational databases

    +

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

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

  • 78 BusinessObjects Advanced Query Building Techniques Guide

    Working wi

    Now you need to link the dimensions in this second data provider (called Revenue) to the equivalent dimensions in the first data provider (called Hierarchy) as follows:

    Dimension in Hierarchy data Linked dimension in Revenue th Hierarchies

    The final step is to create a variable, hierarchy_revenue, that calculates the revenue for each item in the hierarchy. The formula for this variable is:If = 0 Then Sum ( In ) Else If = 1 Then Sum ( In ( ,)) Else Sum ( In ( , , )) This formula uses the If Then Else construction to check the level of each item in the hierarchy (by checking the value of the item_level variable). It then uses extended calculation syntax to aggregate the revenue at the appropriate level, as shown in the following table. (For more information about extended calculation syntax see Understanding Calculation Contexts on page 15.)

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

    provider data providerhierarchy_country Country of origin

    hierarchy_region Region

    hierarchy_city City

    Level Calculation input contextCountry 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 as follows:Hierarchies in relational databases

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

  • 80 BusinessObjects Advanced Query Building Techniques Guide

    Working wi

    Reporting at different levels of the hierarchyOne of the advantages of this kind of hierarchical display is the ability to report on several levels of the hierarchy simultaneously. You have already seen how you can display revenue for countries, regions and cities in the same column by th Hierarchies

    creating a separate data provider and using extended calculation syntax. You can do this with many different sorts of calculations.

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

  • BusinessObjects Advanced Query Building Techniques Guide 81

    The result is as follows: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

    Working with Hierarchies

  • rAdvanced SQL Generationchapte

  • 84 BusinessObjects Advanced Query Building Techniques Guide

    Advanced

    OverviewThis chapter deals with advanced SQL generation techniques in Designer that SQL Generation

    you can use to create objects tailored to your needs.

  • 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 the object SQL: The Edit Properties of dialog box and the Tables dialog box. In SQL generation in Designer

    the first of these dialog boxes you enter the SELECT statement in the Select box and the WHERE clause in the Where box. You use the Tables dialog box to determine which tables will appear in the FROM clause. For example, the Region object in the Island Resorts Marketing universe references the Region column of the Region table in the SELECT box, and the Region table in the Tables dialog box.

    If you add a WHERE that restricts the regions to West, the generated SQL looks like this: SELECT Region.regionFROM RegionWHERE

    ( Region.region = 'West' )

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

  • 86 BusinessObjects Advanced Query Building Techniques Guide

    Advanced

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

    Creating a dummy tableSQL Generation

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

    You define a ServerVersion object as follows:

  • BusinessObjects Advanced Query Building Techniques Guide 87

    Including and ORDER BY clause in generated SQLHow can you include other clauses such as ORDER BY and GROUP BY in SQL generated by Designer? What if you want to create an object that returns all the distinct invoice years in the Island Resorts Marketing database, sorted in SQL generation in Designer

    ascending order by the database? The SQL to do this is:SELECT DISTINCT datepart (year, invoice_date) as invoice_yearFROM salesORDER BY invoice_year

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

  • 88 BusinessObjects Advanced Query Building Techniques Guide

    Advanced

    Designer generates the following SQL based on the text you typed in the Edit Properties Of dialog box:SELECT

    distinct datepart (year, invoice_date) as invoice_year

    Usin

    Wha

    InlinSQL Generation

    FROM

    Sales

    WHERE

    ( 1=1 ) order by invoice_year -- )This SQL returns the pre-sorted list of invoice years.

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

    t are inline aliases?Inline aliases allow you to alias a block of SQL within a larger query and than select columns from that block. For example, the SQL to return the names of user-created tables in a SQL Server database is SELECT name

    FROM sysobjectsWHERE type = u

    This could be expressed, using an inline alias, asSELECT *

    FROM (SELECT name FROM sysobjects WHERE type = U) sysobjects_aliaswhere the original query is aliased as sysobjects_alias.

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

  • BusinessObjects Advanced Query Building Techniques Guide 89

    EXAMPLEUsing a derived table to build a visual hierarchyIn this example you use a derived table to build the visual hierarchy that you built SQL generation in Designer

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

  • 90 BusinessObjects Advanced Query Building Techniques Guide

    Advanced

    The first thing you need to do is to build the SQL that will return a result set showing all the hierarchy items, their level in the hierarchy, and their sort order. The following SQL does this:select country as hierarchy_country, NULL as hierarchy_region,SQL Generation

    NULL as hierarchy_city, 0 as item_level, country as order_colfrom countryunionselect c.country as hierarchy_country, region as hierarchy_region, NULL as hierarchy_city, 1 as item_level, c.country + r.region as order_colfrom region r, country cwhere c.country_id = r.country_idunionselect 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_colfrom city c, region r, country c2where 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 that Designer uses when building the SQL.SQL generation in Designer

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

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

  • 92 BusinessObjects Advanced Query Building Techniques Guide

    Advanced

    When you create these objects, hierarchy appears in the list of tables in exactly the same way as the physical database tables. When Designer generates the SQL for an object, it aliases the SQL used to build the derived table with the name of the derived table. For example, the SQL for SQL Generation

    the hierarchy_country object is as follows:SELECT

    hierarchy.hierarchy_country FROM

    (derived_table_sql) hierarchyYou can now build a visual hierarchy using these objects. The approach is the same as you used with free-hand SQL in the chapter Working with Hierarchies on page 71. See that chapter for more detailed explanations of the steps in the following procedure.To build a hierarchy using the objects you have created:1. Create a block using all the hierarchy objects.

    Designer generates the following SQLto build the block:SELECT hierarchy.hierarchy_country, hierarchy.hierarchy_region, hierarchy.hierarchy_city, hierarchy.item_level, hierarchy.order_colFROM ( derived_table_sql) hierarchy

    2. Sort the table on the order_col column.3. Create a hierarchy_display object that indents the objects in the

    hierarchy.4. Delete all columns in the block except for hierarchy_display.5. Create an alerter to format the rows depending on the object level in the

    hierarchy.

  • BusinessObjects Advanced Query Building Techniques Guide 93

    IndexBBusin

    cdDst

    Ccalcu

    dconsu

    Bcusto

    Ddemo

    mDevedocum

    Cfoprs

    Docu

    Eeducaexten

    d

    Ffeedb

    oIndexess Objectsonsulting services 11, 13ocumentation 10ocumentation Supply Store 9upport services 11raining services 11, 13

    lation contextefined 17ltantsusiness Objects 11

    mer support 11

    aterials 9loper Suite 10, 12

    entationD 9

    eedback on 10n the web 9rinted, ordering 9oadmap 9earch 9mentation Supply Store 9

    tion see trainingded calculation syntaxefined 18

    ackn documentation 10

    Iinput contexts

    defined 18

    KKnowledge Base 12

    Mmultimedia

    quick tours 10

    OOnline Customer Support 11output contexts

    defined 19

    Ssearch

    documentation 9support

    customer 11

    TTips & Tricks 10training

    on Business Objects products 11

    Wweb

    customer support 11getting documentation via 9useful addresses 12

  • 94 BusinessObjects Advanced Query Building Techniques Guide

    Index

    BusinessObjects Advanced Query Building Techniques GuideContentsExamplesMaximizing Your Information ResourcesInformation, services, and solutionsInformation resourcesWhere do I start?How can I get the most recent documentation?Send us your feedback

    ServicesHow we can support you?Having an issue with the product?Looking for the best deployment solution for your company?Looking for training options?

    Useful addresses at a glanceAbout this guideAudienceConventions used in this guide

    Understanding Calculation ContextsDefining the calculation contextWhat are calculation contexts?

    What is extended syntax?Input and output contextsExtended syntax context operators

    Extended syntax keywordsFuture-proofing of reportsSimplification of formulasList of keywordsTesting formulas with extended syntax

    Subqueries in BusinessObjectsUsing subqueries in the Query PanelComparing subqueries and extended calculation syntaxDimension restrictions in subqueries

    Creating subqueries by using complex conditions

    Working with PromptsCreating meaningful LOVs in promptsCreating a Revenue by Day objectMapping function arguments to labelsCreating the lookup tableCreating the objectRunning a reportThe object WHERE clause

    Creating an ALL option in a promptAdding ALL to an object list of values

    Building Date-Related QueriesA technique for date-related queriesUsing the dates tableCreating universe objectsAccounting for holiday days

    Working with HierarchiesHierarchies in relational databasesBuilding a hierarchy result setDisplaying the hierarchy in BusinessObjectsAdding measures to the hierarchyReporting at different levels of the hierarchy

    Advanced SQL GenerationSQL generation in DesignerCreating a dummy tableIncluding and ORDER BY clause in generated SQLUsing derived tablesWhat are inline aliases?Inline aliases and derived tables

    Index