简体   繁体   中英

Calculate Difference in Dates that are in Rows for Power BI

I am a very new user to Power Bi. I have a table with 3 columns of data and I need to calculate the days between the Dates Column.

An Example of Data Below: Would like to add a column with time in days that it took to go from first line of data to the next. But then needs to restart the count when the Deal Id changes.

Deal Id Unique Id   Stage Start Date    
4409    17525   9/7/2021    
4409    17529   9/7/2021    
4409    18125   9/12/2021   
4409    18547   9/12/2021   
4409    21539   9/29/2021   
4409    21741   10/1/2021   
4409    22167   10/5/2021   
4409    22173   10/5/2021
4409    23883   10/15/2021  
4433    17459   9/7/2021    
4433    17531   9/7/2021    
4433    37001   9/10/2021

please check my solution:

You need to add 2 new columns (Calculated Columns) to achieve your result:

First Column To find out the minimum date by [Deal Id] column:

MinDate =
CALCULATE (
    MIN ( YourTable[Stage Start Date] ),
    ALLEXCEPT ( YourTable, YourTable[Deal Id] )
)

Second Column to find the difference in days between newly created [MinDate] and [Stage Start Date] columns:

DaysPassed =
DATEDIFF ( [MinDate], [Stage Start Date], DAY )

If we test the codes, It returns:

GGGG

Note: 4409 and 4433 Deal id both have the same minimum dates, so our Mindate column show the same value for all data.

You can do this easily in the Query Editor Home=>Transform Data

Open the Advanced Editor and paste the code below into the window that opens.

Retain the first line ( Source ) of your existing to replace the Source line in the code below.

The code assumes the data is already sorted ascending by Date. If it is not, you can just insert that step.

let

//Change next line to reflect actual data source
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Deal Id", Int64.Type}, {"Unique ID", Int64.Type}, {"Stage Start Date", type date}}),

//Group by Deal ID
    #"Grouped Rows" = Table.Group(#"Changed Type", {"Deal Id"}, {
        
//Add column to each sub-table that subtracts the first date from the date in the current row
        {"Days", 
            (t)=>Table.AddColumn(t, "Elapsed Days", each Duration.TotalDays([Stage Start Date] - t[Stage Start Date]{0}), Int64.Type), 
                type table[Unique ID=text, Stage Start Date=date, Elapsed Days=Int64.Type]}
       }),
    #"Expanded Elapsed Days" = Table.ExpandTableColumn(#"Grouped Rows", "Days", {"Unique ID", "Stage Start Date", "Elapsed Days"})
in
    #"Expanded Elapsed Days"

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM