Home › Discussions › Questions & Answers › Dynamic Column Generation for SQL Pivot Tables

Dynamic Column Generation for SQL Pivot Tables

Avatar photoCustomer Questions & Answers 7 replies

I need to build a financial report based on GL balances where the column list (representing periods) must change dynamically based on user input, creating a SQL Pivot table. How should I structure the SQL and parameters using Blitz Report features?

7 replies

  • Support Enginatics

    Dynamic pivot tables require the &lexical parameter reference, as it allows for the insertion of variable SQL snippets, which is necessary for the column list in the PIVOT clause. In the example of GL Balances, the PIVOT clause structure is `pivot(sum(amount) for period_name in (&gl_period_pivot))`.

  • So the lexical anchor, say `&gl_period_pivot`, must be defined by a parameter that returns the necessary column list. What kind of output does that parameter SQL text need to generate?

  • Support Enginatics

    The parameter SQL text needs to generate a comma-separated list of periods, formatted correctly for the PIVOT clause, which typically includes aliases. For instance, if the Period parameter derives the year, the lexical reference might be replaced with: `’Jan-20′ jan_2020, ‘Feb-20’ feb_2020, ‘Mar-20’ mar_2020, …`. The resulting list contains periods from the first of the derived year up to the period indicated in the input parameter.

  • If I also need a normal WHERE clause restriction, like restricting by Ledger name, should I also use a lexical anchor?

  • Support Enginatics

    For the Ledger name restriction, you should use an `n=n` anchor (like `1=1`). In the GL Balance pivot example, the main query includes `where 1 = 1 and gl.ledger_id = gb.ledger_id`. The Ledger restriction parameter would insert its clause at the `1=1` position, while the dynamic period list is inserted at `&gl_period_pivot`.

  • If I am using an &lexical anchor to dynamically select Descriptive Flexfield (DFF) columns, is there a utility function available for that?

  • Support Enginatics

    Yes, for DFFs, you can use the `XXEN_UTIL.DFF_COLUMNS` function. This function returns a SQL text snippet, such as `msiv.attribute15 “Invoice UOM”,` designed to replace an `&lexical` placeholder like `&flexfield_columns` in your main `SELECT` statement. This ensures the column names use the DFF’s form left prompt as the alias.

  • You must be logged in to reply to this post.