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

Dynamic Column Generation for SQL Pivot Tables

Avatar photoCustomer January 31, 2022 at 11:56 pm

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?

Viewing 6 reply threads
  • Author
    Replies
    • Support February 1, 2022 at 10:13 am  

      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))`.

    • Avatar photoCustomer February 2, 2022 at 2:57 am  

      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 February 4, 2022 at 12:07 am  

      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.

    • Avatar photoCustomer February 5, 2022 at 10:07 pm  

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

    • Support February 7, 2022 at 8:51 pm  

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

    • Avatar photoCustomer February 8, 2022 at 11:25 pm  

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

    • Support February 10, 2022 at 5:28 am  

      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.

Viewing 6 reply threads
  • You must be logged in to reply to this post.

Login with: