Dynamically add month columns and conditional values in PQ

JGordon11

Well-known Member
Joined
Jan 18, 2021
Messages
814
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
How would one use PQ to transform the table on the left into the table on the right?

Book2
ABCDEFGHIJKL
1ItemStartEndAmountItemFebruary 2021March 2022April 2021May 2021June 2021July 2021
212/1/20214/30/2021501505050
323/1/20216/30/20211002100100100100
434/1/20217/31/202175375757575
Sheet1
 

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
I'm sure there are better ways, but something like this should work:

Power Query:
let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Item", Int64.Type}, {"Start", type date}, {"End", type date}, {"Amount", Int64.Type}}),
    #"Added Custom" = Table.AddColumn(#"Changed Type", "MonthList", each let dateFrom = [Start], dateTo = [End] in List.Generate(()=>dateFrom, each _ < dateTo, each Date.AddMonths(_, 1))),
    #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Start", "End"}),
    #"Expanded MonthList" = Table.ExpandListColumn(#"Removed Columns", "MonthList"),
    #"Pivoted Column" = Table.Pivot(Table.TransformColumnTypes(#"Expanded MonthList", {{"MonthList", type text}}, "en-GB"), List.Distinct(Table.TransformColumnTypes(#"Expanded MonthList", {{"MonthList", type text}}, "en-GB")[MonthList]), "MonthList", "Amount", List.Sum)
in
    #"Pivoted Column"
 
Upvote 0
Solution
Thanks - your Table.AddColumn step was where I was going to great and mostly unproductive lengths to try to accomplish.
 
Upvote 0

Forum statistics

Threads
1,215,291
Messages
6,124,093
Members
449,142
Latest member
championbowler

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top