Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Crosstab Union Queries for Charts

Crosstab Union Queries for Charts.

When preparing charts in Excel, source data is either entered directly into cells or linked to specific worksheet locations where summary figures are available. The arrangement of these values is planned in advance and entered in the required order, depending on the chart type. Charts are then created from this data as a final step, either for printing or presentation purposes.

In most cases, this is a one-time task. However, if updates are needed—such as adding another month’s data to a month-wise chart—you must adjust the physical arrangement of the data and update the chart’s Data Series Range so the new values appear.

If space for all twelve months is allocated in advance but actual data is only available up to March, the remaining nine months in the chart will appear blank.

Preparing Data for the Chart.

When preparing charts in MS Access, we first need to shape the data into a format that can be used directly in the chart. This is done using queries. The process can be automated by running action queries through macros, making it essentially a one-time setup.

Partially prepared summary data can then be further refined with other queries, such as crosstab or union queries, to format it for charting purposes. These queries can automatically transform newly added rows in the summary source table into new columns, ensuring that charts update instantly to reflect the changes.

Once a chart is created from such queries, it continues to work without further adjustments—your chart is always ready with updated values.

Next, we will explore how crosstab and union queries can be used to shape summary data for bar charts and line charts. For this example, we will assume that the Profitability Summary data for Branch 1, shown below, was prepared using action queries such as Make Table and Append queries.

Table Name: Profitability
Location PYear PMth Revenue Expenses
Branch1 2008 1 $25,000 $5,000
Branch1 2008 2 $35,000 $7,500
Branch1 2008 3 $15,000 $4,000
Branch1 2008 4 $40,000 $15,000

The summary data above is reformatted for the chart below using a combination of Select, Crosstab, and Union queries. In this setup, each Crosstab query extracts and structures the Revenue, Expenses, and Income values. These are then merged in a final Union query, which serves as the direct data source for the chart. This approach ensures the chart updates automatically whenever the underlying summary data changes.

Step 1 – Create the Summary_inQ Query

The first step is to format the Year and Month values, calculate the last date of the month, and use this date on the chart’s X-axis.

We will create a Select query named Summary_inQ based on the Profitability table.

  1. Open a new query in Design View.

  2. Do not select any tables or queries from the displayed list.

  3. From the View menu, choose SQL View.

  4. Copy and paste the following SQL into the SQL editor:

    sql
    SELECT 
    
    Profitability.*,
    DateValue([pyear] & "-" & [pmth] & "-01") AS dt,
    DateAdd("m",1,[dt])-1 AS MonthLastDate
    FROM Profitability;
  5. Save the query as Summary_inQ.

  6. The Summary_inQ Query in DataSheet View is given below:

  7. Tip: I like to include the letter Q in query names, or words like Cross or Union, to make them easy to identify when mixed in with table names.

    When new data (e.g., for May, June, and later months) is added to the Profitability table, they will automatically appear in the Summary_inQ and the other Crosstab Queries.

    Step 2 – Create the Crosstab Queries.

    We will now create three Crosstab queries — one each for Revenue, Expenses, and Income.

    Follow these steps for each Crosstab query:

    1. Open a new query in Design View.

    2. Do not select any tables or queries from the displayed list.

    3. Switch to SQL View.

    4. Copy and paste the SQL string for the query you are creating.

    5. Save the query with the name shown.

    1. Revenue Crosstab – CrossRevenueQ

    sql
    TRANSFORM Sum(Summary_inQ.Revenue) AS SumOfRevenue SELECT "1Revenue" AS [Desc] FROM Summary_inQ GROUP BY "1Revenue" PIVOT Summary_inQ.MonthLastDate;

    2. Expenses Crosstab – CrossExpensesQ

    sql
    TRANSFORM Sum(Summary_inQ.Expenses) AS TotalExpenses SELECT "2Expenses" AS Category FROM Summary_inQ GROUP BY "2Expenses" PIVOT Summary_inQ.MonthLastDate;

    3. Income Crosstab – CrossIncomeQ

    sql
    TRANSFORM Sum([Revenue]-[Expenses]) AS Expr1 SELECT "3Income" AS [Desc] FROM Summary_inQ GROUP BY "3Income" PIVOT Summary_inQ.MonthLastDate;

    Note on naming:
    In the SELECT clause of each SQL statement, you will see a number prefixed to the category name:

    • 1Revenue

    • 2Expenses

    • 3Income

    This ensures that when the queries are combined in a Union query, the results are sorted in the logical order (Revenue → Expenses → Income) instead of alphabetical order, which would place Expenses first, Income in the middle, and Revenue last.

    Step 3 – Create the Union Query

    Finally, we will combine all three Crosstab queries into a single Union query, which will serve as the chart’s source.

    1. Open a new query in Design View.

    2. Do not select any tables or queries from the list.

    3. Switch to SQL View.

    4. Copy and paste the following SQL string into the SQL editor:

    sql
    SELECT * FROM CrossRevenueQ UNION ALL SELECT * FROM CrossExpensesQ UNION ALL
    SELECT * FROM CrossIncomeQ;
    1. Save the query with the suggested name — for example: UnionSummaryQ.

    2. UnionSummaryQ Query output in Datasheet View is given below: 


      Designing the Chart.

      Now, all that is left to do is to design a Chart using the UnionSummaryQ Query. Instead of repeating the same procedure that I have already explained earlier, you can go to the Next Page and continue there from Step 4 onwards. Change the Property Value Row Source = BarChartQ to Row Source = UnionSummaryQ and continue with creating the Chart and formatting it as explained there. Make changes to the Titles and other formatting options to make the finished Chart look like the sample given above.

      1. MS-Access and Graph Charts
      2. MS-Access and Graph Charts-2
      3. Working With Chart Objects in VBA
      4. Column Chart and VBA
      5. Pie Chart Object and VBA
      6. Missing Lines in Line-Chart
      7. Pie Chart and Live Data on Form
      8. Scaling Chart Object
      9. Cross-Tab Union Queries for Chart
Share:

No comments:

Post a Comment

Comments subject to moderation before publishing.

PRESENTATION: ACCESS USER GROUPS (EUROPE)

Translate

PageRank

Post Feed


Search

Popular Posts

Blog Archive

Powered by Blogger.

Labels

Forms Functions How Tos MS-Access Security Reports msaccess forms Animations msaccess animation Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet Class Module External Links Queries Array msaccess reports Accesstips WithEvents msaccess tips Downloads Objects Menus and Toolbars Collection Object MsaccessLinks Process Controls Art Work Property msaccess How Tos Combo Boxes Dictionary Object ListView Control Query VBA msaccessQuery Calculation Event Graph Charts ImageList Control List Boxes TreeView Control Command Buttons Controls Data Emails and Alerts Form Custom Functions Custom Wizards DOS Commands Data Type Key Object Reference ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button Report msaccess menus msaccessprocess security advanced Access Security Add Auto-Number Field Type Form Instances ImageList Item Macros Menus Nodes RaiseEvent Recordset Top Values Variables Wrapper Classes msaccess email progressmeter Access2007 Copy Excel Export Expression Fields Join Methods Microsoft Numbering System Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup database function msaccess wizards tutorial Access Emails and Alerts Access Fields Access How Tos Access Mail Merge Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting ChDir Color Palette Common Controls Conditional Formatting Data Filtering Database Records Defining Pages Desktop Shortcuts Diagram Disk Dynamic Lookup Error Handler External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Message Box Monitoring Octal Numbers Operating System Paste Primary-Key Product Rank Reading Remove Rich Text Sequence SetFocus Summary Tab-Page Union Query User Users Water-Mark Word automatically commands hyperlinks iSeries Date iif ms-access msaccess msaccess alerts pdf files reference restore switch text toolbar updating upload vba code