Forum Discussion

jakoob's avatar
jakoob
Frequent Visitor
3 years ago

Pivot in Power Query Help

Hello,

 

I'm currently working with some customer satisfaction data that currently looks similar to the following:

Sent Survey IDSurvey Question IDAnswerSurvey ID
11Less than 30 minutes4
1254
13Yes4
1454
21Less than 30 minutes4
2254
23Yes4
2454
31Less than 30 minutes4
3254
33Yes4
3454

 

In the above table, each value in the column "Sent Survey ID" represents a single customer survey. The issue is that currently, a single survey is split across multiple rows in the table. I need to be able to perform aggregations, such as averages for each "Survey Question ID" question and answer (Example: Average score of 5 for Question ID 2). Ideally, my goal is to have a table that looks like the following below with a single survey being included on a single row:

Sent Survey IDQuestion 1 AnswerQuestion 2 AnswerQuestion 3 AnswerQuestion 4 AnswerSurvey ID
1Less than 30 minutes5Yes54
2Less than 30 minutes5Yes54
3Less than 30 minutes5Yes54

 

My thought was to Pivot the "Survey Question ID" column from the first table above in Power Query, with the attributes set to the "Answer" column also from the first table. However when I do so, I get a table that looks like the following:

Sent Survey IDQuestion 1 AnswerQuestion 2 AnswerQuestion 3 AnswerQuestion 4 AnswerSurvey ID
1Less than 30 minutesnullnullnull4
1null5nullnull4
1nullnullYesnull4
1nullnullnull54
2Less than 30 minutesnullnullnull4
2null5nullnull4
2nullnullYesnull4
2nullnullnull54
3Less than 30 minutesnullnullnull4
3null5nullnull4
3nullnullYesnull4
3nullnullnull54

 

While this above table would meet my requirements, which is to be able to perform aggregation on each answer column, its not optimized best with all the excess rows that contain null values in the question columns.

 

Is there a better way to accomplish what I am trying to achieve?

 

Thank you in advance!

2 Replies

  • Hi,

    This M code works

    let
        Source = Excel.CurrentWorkbook(){[Name="Data"]}[Content],
        #"Added Prefix" = Table.TransformColumns(Source, {{"Survey Question ID", each "Question " & Text.From(_, "en-IN"), type text}}),
        #"Added Suffix" = Table.TransformColumns(#"Added Prefix", {{"Survey Question ID", each _ & " Answer", type text}}),
        #"Pivoted Column" = Table.Pivot(#"Added Suffix", List.Distinct(#"Added Suffix"[#"Survey Question ID"]), "Survey Question ID", "Answer")
    in
        #"Pivoted Column"

    Hope this helps.