• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Unpivot data

Lara_1234

New Member
Hi experts, i have below data which i need to unpivot by year

Country2013 Account2013Unit2013rate2013cost2014Group Account2014Unit2014rate2014cost2015Group Account2015Unit2015rate2015cost
UKABC101215HIJ192124QRS384043
UKBCD111316KLM202225TUV394144
UKEFG121417NOP212326WXY404245
 
Power Query result at cell R3, pivot from that table at cell X4 in the attached.

1714132420861.png
 

Attachments

  • Chandoo56801BR.xlsx
    24 KB · Views: 3
This addresses the problem using Excel 365 formulas and is not for the faint-hearted!

The first step was to create a Lambda function that would extract the data for a single year as a function (a thunk).
Code:
/*  FUNCTION NAME:  ExtractYrDataλ
    DESCRIPTION:    Looks up and extracts 1 year's data from table as a thunk*/
/*  REVISIONS:      Date            Developer           Description
                    27 Apr 2024     Peter Bartholomew   Original Development
*/

ExtractYrDataλ = LAMBDA(
//Parameter Declarations
    hdr,            //Header row to crosstab table
    body,           //Body of crosstab table
    LAMBDA(
    yr,             //Year of data to be extracted
    LAMBDA(
        LET(
            firstField, XLOOKUP(yr&"*", hdr, body,,2, 1),
            finalField, XLOOKUP(yr&"*", hdr, body,,2,-1),
            IFERROR(HSTACK(yr, firstField:finalField), "")
        )
    )
))
The function looks up the first and final fields corresponding to the given year and composes the range using the ":" operator. It appends the year and thunks the result. The result is shown as the first formula on the worksheet.
1714253877522.png

That formula is

Code:
= ExtractYrDataλ(Table1[#Headers], Table1)(2014)()

The second formula shows how the thunk array is built
Code:
= MAP({2013; 2014; 2015},
    ExtractYrDataλ(Table1[#Headers], Table1)
  )

The final formula brings this together
Code:
=LET(
    yrTblϑ, MAP({2013; 2014; 2015}, ExtractYrDataλ(Table1[#Headers], Table1)),
    output, REDUCE(
        {"Year", "Account", "Unit", "Rate", "Cost"},
        yrTblϑ,
        LAMBDA(stack, ϑ, VSTACK(stack, ϑ()))
    ),
    output
)
REDUCE is used to feed the elements of the thunk array into the lambda function one by one where they are evaluated and stacked.

If this looks like pretty heavy programming than spreadsheet authoring, that is not far from the truth! The amazing thing is that it works!
 

Attachments

  • Chandoo56801BR.xlsx
    33.3 KB · Views: 0
Last edited:
Back
Top