Forum Discussion

JMelo's avatar
JMelo
Frequent Visitor
7 years ago
Solved

Power Query: Count Months within Date Interval, by Year

Good evening eveyone!   I have a challenge where i need to count the amount of months each row   For each row i have a start date and end date.   Start Date: 04/01/2016 End Date: 12/01/2018  ...
  • sanimesa's avatar
    sanimesa
    7 years ago

    Not a complete solution!

     

    I am assuming you want a generic way to add columns given any two dates. You can use List.Generate to run a loop for all the years between start and end dates and then within the loop add the column. A reference for the concept is below:

    https://potyarkin.ml/posts/2017/loops-in-power-query-m-language/

     

    As for syntax of adding the column you require, you can play with the Add Column from the menu options. Here is an example (after manually entering data):

     

    let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WCkktLlEwNDJW0lEyMNE3MNQ3MjA0A3IMjaAcC6XYWAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [#"Contract Name" = _t, #"Start Date" = _t, #"End Date" = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Contract Name", type text}, {"Start Date", type date}, {"End Date", type date}}),
    #"Added Custom" = Table.AddColumn(#"Changed Type", "Months in 2016", each 12 - Date.Month([Start Date]))
    in
    #"Added Custom"