Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Compete to become Power BI Data Viz World Champion! First round ends August 18th. Get started.

Reply
mail2rohitnagar
Regular Visitor

Need help with calculated column

I have a usecase to calculate corrected target based on the previous month variance. Below is my scenario

 

Column Name

Values(M1)

Values(M2)Values(M3)
Sales Person NameJohnJohnJohn
ParticularPowerBIPowerBIPowerBI
Month456
Year202520252025
Unique IDJOHN_POWERBI_4_2025JOHN_POWERBI_5_2025JOHN_POWERBI_6_2025
Target (Cr)342
Actual Sales(cr)1.33.10.1
Corrected Target (Cr) (Current month Target+Variance (Prev. Month)) 5.74.6
Variance (Cr) - (Corrected Target - Actual Sales)1.72.64.5

Let me know how to do this in power bi report either as a claulated colum or as a measure

1 ACCEPTED SOLUTION

Hi 

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("1djbbtowAAbgV0G5hsgH4oTLduukIjFQe9GLqqooyzYkaKoUOu1mF3urvc6eZHYI1A7GJwXHk1pyahM+nIQ///19NIz6EQIooZO75Wq1nK/p3KwsvmwXm1c6Oy6+P9PJZLkoi9fi66YxP8WE/evf3396OAbZfhb0M4z7GNN1gK4DMaxeMZtgQLfFGLMDJ78QoVP6c/FSDqp3wQ74yHb7COAADAf1m2O7hXGa9T6UdKm3PyC3COixdoswxqA3oOvYrh/691ESCHIy/ylDJjzynaFGVhtqJNsyjHFWYUkg2PH2WYYlIhYTEyyKU8RjSQzTCpsGg13JsCmPxYYjCxojm8QZrLBZINiL7TcZNmvjNMb7kR0Fgr3NX2TYURvYw2kMQSDa6WIj0ULQrhYGov1cvMm0sF0tCkT7MV/ItKhd7Q5LusaO5/TbhxxdttXQkrawKBDsp/xJhkWtYnEg2Mm8lGFxq1guFt8UT3nJBLd5+bZc5AbWWfEjLy+vD28GpvUs7BNC6G+61+LqFbDjJKBadzITz6Z3VzeX18exuIFlhzuRK+gG4auW7qIRj7vDitmYx6risTGWbWnG4+6wYjbmsaQdLL1oGvG4S+zqBDZtFZuFgBWzMY9txmNoiCVS7CgErJiNeawqHtuMLDqKx91pxWzMaZXx2P485uNxd1oxG/NaVTx20KIQtGI25rWqeOygjQ4hqsMbspCN+cu2GY+xIXYoxaIQsGI25rGqeGwzsqAZj7sMUeUJrCoe25/Gutb4ar2eK7TcswA6e2sMxNYYmbTGuz88jsedYk3aYxRnwARbfzDofQmb9se+uA79sWJsxf6YfUxG/bE/rHV/rBnbkTC2NVfXIHu7bu0b5JNcdNQg1096ugbZF9ahQTbGDunzgVmD7Evr0CA7aHUNsi+tQ4PsoNU1yL60Dg2ygzZS94zebsn2DbI9Vtcg+8I6NMj2WF2D7C9IWTfI9lhNg6yx/h8Nsiwid4c9e4NcP/xoGmQ/2EAaZF/YIBpkT9dsGA2yH2woDbIfbSgNsh9tKA2yH61hgwwNtbulDPNLZh2yp1vyeTtkuH+I13TIfrCBdMi+YpSHDvnhHw==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [MONTH = _t, YEAR = _t, #"PRINCIPAL MANAGERS" = _t, #"PROD/ SERVICE" = _t, #"SALES PERSON" = _t, PRINCIPAL = _t, PRATICULARS = _t, REFERENCE = _t, #"REV, RS. LAKHS" = _t, REV = _t, #"MARGIN %" = _t, #"MARGIN (RS. LAKHS)" = _t, MARGIN = _t, #"Financial Year" = _t, #"BUD. / ACT." = _t, #"MONTH YEAR" = _t, #"Unique Id" = _t, #"Actual Sales" = _t, #"Target in Cr" = _t, #"Target Margin in Cr" = _t, Variance = _t, CorrectedTarget = _t]),

    
    Clean1 = Table.ReplaceValue(Source, "₹", "", Replacer.ReplaceText, {"Target in Cr", "Actual Sales"}),
    Clean2 = Table.ReplaceValue(Clean1, "Cr", "", Replacer.ReplaceText, {"Target in Cr", "Actual Sales"}),

  
    ChangedTypes = Table.TransformColumnTypes(Clean2, {
        {"MONTH", Int64.Type}, {"YEAR", Int64.Type},
        {"Target in Cr", type number}, {"Actual Sales", type number}
    }),

    
    #"Removed Old CT" = Table.RemoveColumns(ChangedTypes, {"CorrectedTarget"}),

    
    Sorted = Table.Sort(#"Removed Old CT", {
        {"SALES PERSON", Order.Ascending},
        {"PRATICULARS", Order.Ascending},
        {"YEAR", Order.Ascending},
        {"MONTH", Order.Ascending}
    }),

  
    Columns = Table.ColumnNames(Sorted),
    Rows = Table.ToRows(Sorted),

    AddCorrectedTarget = List.Accumulate(
        Rows,
        { {}, 0, null, null },  
        (state, currentRow) =>
            let
                result = state{0},
                prevCT = state{1},
                prevSP = state{2},
                prevPart = state{3},

                salesPerson = currentRow{List.PositionOf(Columns, "SALES PERSON")},
                particular = currentRow{List.PositionOf(Columns, "PRATICULARS")},
                target = try Number.From(currentRow{List.PositionOf(Columns, "Target in Cr")}) otherwise 0,
                actual = try Number.From(currentRow{List.PositionOf(Columns, "Actual Sales")}) otherwise 0,

                isFirst = List.Count(result) = 0 or salesPerson <> prevSP or particular <> prevPart,
                newCT = if isFirst then target else prevCT - actual + target,

                rowWithCT = Record.AddField(Record.FromList(currentRow, Columns), "CorrectedTarget", newCT),
                updatedRows = List.Combine({result, {rowWithCT}})
            in
                {updatedRows, newCT, salesPerson, particular}
    ){0},

    FinalTable = Table.FromRecords(AddCorrectedTarget)
in
    FinalTable


Regards,
Karpurapu D.

View solution in original post

14 REPLIES 14
Poojara_D12
Super User
Super User

Hi @mail2rohitnagar 

To calculate the Corrected Target and Variance in Power BI based on the previous month’s performance, you can approach this by creating calculated columns in your table, especially since your data appears to be in a flat structure with one row per salesperson, per product, per month. The corrected target is calculated as the current month's target plus the variance from the previous month, where the variance is defined as previous month’s target minus actual sales. Since this logic requires referencing the previous row (i.e., the same salesperson and product in the previous month), you can use DAX with functions like EARLIER() and FILTER() to look back at the corresponding record for the previous month. First, you calculate the previous month’s variance by filtering the table for the same salesperson, same product, same year, and one month earlier, then subtracting actual sales from the target for that month. Next, you add that previous variance to the current month’s target to get the corrected target. Finally, you compute the current month’s variance as the difference between the corrected target and actual sales. This approach works well with calculated columns when your data is in a row-by-row format. If you were working with a more dynamic or time-aware model (e.g., using slicers or visuals based on a calendar), then measures with a proper date table and time intelligence functions like DATEADD or PREVIOUSMONTH would be more appropriate.

 

Did I answer your question? Mark my post as a solution, this will help others!
If my response(s) assisted you in any way, don't forget to drop me a "Kudos"

Kind Regards,
Poojara - Proud to be a Super User
Data Analyst | MSBI Developer | Power BI Consultant
Consider Subscribing my YouTube for Beginners/Advance Concepts: https://youtube.com/@biconcepts?si=04iw9SYI2HN80HKS
v-karpurapud
Community Support
Community Support

Hi @mail2rohitnagar 

We are following up once again regarding your query. If the issue has been resolved,kindly mark the helpful response and accept it as the solution to assist other community members in resolving similar issues more efficiently. If not, please provide detailed information so we can better assist you.

 

 

Thank you for your understanding and participation.

 

v-karpurapud
Community Support
Community Support

Hi @mail2rohitnagar 

We have not yet received a response from you regarding your query if you find the response helpful, kindly mark it as the accepted solution and provide kudos, as this will aid other members with similar queries.

 

Thank You.

v-karpurapud
Community Support
Community Support

Hi @mail2rohitnagar 

I wanted to check if you had the opportunity to review the information provided. Please feel free to contact us if you have any further questions. If my response has addressed your query, please accept it as a solution and give a 'Kudos' so other members can easily find it.

Thank you.

v-karpurapud
Community Support
Community Support

Hi @mail2rohitnagar 

Welcome to the Microsoft Fabric Community Forum!


To create a measure for calculating the Corrected Target based on the previous month's variance, implement a DAX formula that dynamically adjusts the current month's target by adding the difference between the previous month's target and actual values, ensuring it supports month-to-month transitions including year rollovers and accurately reflects both row-level and aggregate totals across Sales Person and specific groupings.


Please refer to the attached .pbix file for your reference and share your thoughts.


Thank you.

Hi,

Thank you for the working file, but it is not matching with the desired result. Variance of month 1 needs to added to the corrected target of month 2 for the same sales person and particular. you can check my attached excel from the previous comment where i have highleted the desired result in column V (Corrected Target)

Hi @mail2rohitnagar 

I have updated the .Pbix as per your requirement. Please take a movement to review it and let us know if you need any adjustments.

vkarpurapud_0-1751971080587.png


Regards,
Karpurapu D,
Microsoft Fabric Community Support Team.

 



hi,

unable to see the formula

 

Hi 

let
    Source =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tbulDPNLZh2yp1vyeTtkuH+I13TIfrCBdMi+YpSHDvnhHw==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [MONTH = _t, YEAR = _t, #"PRINCIPAL MANAGERS" = _t, #"PROD/ SERVICE" = _t, #"SALES PERSON" = _t, PRINCIPAL = _t, PRATICULARS = _t, REFERENCE = _t, #"REV, RS. LAKHS" = _t, REV = _t, #"MARGIN %" = _t, #"MARGIN (RS. LAKHS)" = _t, MARGIN = _t, #"Financial Year" = _t, #"BUD. / ACT." = _t, #"MONTH YEAR" = _t, #"Unique Id" = _t, #"Actual Sales" = _t, #"Target in Cr" = _t, #"Target Margin in Cr" = _t, Variance = _t, CorrectedTarget = _t]),

    
    Clean1 = Table.ReplaceValue(Source, "₹", "", Replacer.ReplaceText, {"Target in Cr", "Actual Sales"}),
    Clean2 = Table.ReplaceValue(Clean1, "Cr", "", Replacer.ReplaceText, {"Target in Cr", "Actual Sales"}),

  
    ChangedTypes = Table.TransformColumnTypes(Clean2, {
        {"MONTH", Int64.Type}, {"YEAR", Int64.Type},
        {"Target in Cr", type number}, {"Actual Sales", type number}
    }),

    
    #"Removed Old CT" = Table.RemoveColumns(ChangedTypes, {"CorrectedTarget"}),

    
    Sorted = Table.Sort(#"Removed Old CT", {
        {"SALES PERSON", Order.Ascending},
        {"PRATICULARS", Order.Ascending},
        {"YEAR", Order.Ascending},
        {"MONTH", Order.Ascending}
    }),

  
    Columns = Table.ColumnNames(Sorted),
    Rows = Table.ToRows(Sorted),

    AddCorrectedTarget = List.Accumulate(
        Rows,
        { {}, 0, null, null },  
        (state, currentRow) =>
            let
                result = state{0},
                prevCT = state{1},
                prevSP = state{2},
                prevPart = state{3},

                salesPerson = currentRow{List.PositionOf(Columns, "SALES PERSON")},
                particular = currentRow{List.PositionOf(Columns, "PRATICULARS")},
                target = try Number.From(currentRow{List.PositionOf(Columns, "Target in Cr")}) otherwise 0,
                actual = try Number.From(currentRow{List.PositionOf(Columns, "Actual Sales")}) otherwise 0,

                isFirst = List.Count(result) = 0 or salesPerson <> prevSP or particular <> prevPart,
                newCT = if isFirst then target else prevCT - actual + target,

                rowWithCT = Record.AddField(Record.FromList(currentRow, Columns), "CorrectedTarget", newCT),
                updatedRows = List.Combine({result, {rowWithCT}})
            in
                {updatedRows, newCT, salesPerson, particular}
    ){0},

    FinalTable = Table.FromRecords(AddCorrectedTarget)
in
    FinalTable


Regards,
Karpurapu D.

mail2rohitnagar
Regular Visitor

Thank you for your response. Unfortunately, none of the solution worked. For better understanding of my issue i have made a data set with sample value. Hope this helps

 

Dataset link -  https://docs.google.com/spreadsheets/d/1XHqY2gEVpF9IrqleOmQk52gdwnGLdwuJ/edit?usp=share_link&ouid=10...

Nasif_Azam
Super User
Super User

Hey @mail2rohitnagar ,

To calculate the Corrected Target in Power BI based on the previous month's Variance, you can use DAX either as a calculated column (if the model is at row level per month) or as a measure (if you're working with visuals or aggregations). If you're using a calculated column assume your table is named 'Sales' and columns: SalesPerson, Particular, Month, Year, Target, ActualSales.

 

Step 1: Create a column for Variance:

Variance = 
'Sales'[CorrectedTarget] - 'Sales'[ActualSales]

 

Step 2: Create the Corrected Target column:

CorrectedTarget = 
VAR PrevMonth =
    CALCULATE(
        MAX('Sales'[Month]),
        FILTER(
            'Sales',
            'Sales'[SalesPerson] = EARLIER('Sales'[SalesPerson]) &&
            'Sales'[Particular] = EARLIER('Sales'[Particular]) &&
            'Sales'[Year] = EARLIER('Sales'[Year]) &&
            'Sales'[Month] = EARLIER('Sales'[Month]) - 1
        )
    )

VAR PrevVariance =
    CALCULATE(
        'Sales'[Target] - 'Sales'[ActualSales],
        FILTER(
            'Sales',
            'Sales'[SalesPerson] = EARLIER('Sales'[SalesPerson]) &&
            'Sales'[Particular] = EARLIER('Sales'[Particular]) &&
            'Sales'[Year] = EARLIER('Sales'[Year]) &&
            'Sales'[Month] = PrevMonth
        )
    )

RETURN 'Sales'[Target] + PrevVariance

 

If using a measure, it's more complex because measures are aggregate-level and cannot store previous row context. You can still do it using CALCULATE and FILTER with a measure, but it's less recommended unless used in visuals.

 

For Detailed Information:

Calculated Columns in Power BI

EARLIER Function in DAX

CALCULATE Function in DAX

FILTER Function in DAX

Measures vs Calculated Columns

 

 

If you found this solution helpful, please consider accepting it and giving it a kudos (Like) it’s greatly appreciated and helps others find the solution more easily.


Best Regards,
Nasif Azam

Didn't work, getting an error as there are multiple lines returining for the formula. I have update the data set in the thread to better express my scenario

DataNinja777
Super User
Super User

Hi @mail2rohitnagar ,

 

To achieve your desired calculation for a corrected target in Power BI, you should use DAX measures rather than calculated columns. This approach is more efficient and flexible because the calculation is iterative and depends on values from previous time periods. Measures are evaluated dynamically based on the context of your report visuals, making them ideal for this type of time-based analysis.

First, it is essential to have a proper date table in your model, as time intelligence functions rely on it. If you do not have one, you can create a new table using the following DAX expression. You should adjust the start and end dates to fit your data. After creating the table, right-click on it in the Fields pane and select "Mark as date table," choosing the [Date] column.

DateTable =
ADDCOLUMNS (
    CALENDAR ( DATE ( 2025, 1, 1 ), DATE ( 2026, 12, 31 ) ),
    "Year", YEAR ( [Date] ),
    "MonthNumber", MONTH ( [Date] ),
    "MonthName", FORMAT ( [Date], "mmmm" ),
    "YearMonth", FORMAT ( [Date], "yyyy-mm" )
)

Your main data table, which we can call SalesData, will need a Date column to relate to this new DateTable. You can add this as a calculated column in your SalesData table. Then, in the Model view, create a one-to-many relationship between DateTable[Date] and SalesData[Date].

Date = DATE('SalesData'[Year], 'SalesData'[Month], 1)

With the model prepared, you can create the necessary measures. It is good practice to start with explicit base measures for your core values.

Total Target = SUM('SalesData'[Target (Cr)])
Total Actual Sales = SUM('SalesData'[Actual Sales(cr)])

The logic for your Variance is a running total of the difference between the target and actual sales over time. The following measure calculates this cumulative value. It works by summing the [Total Target] - [Total Actual Sales] difference over a modified date context that includes all dates up to the last date of the current period being evaluated in your visual.

Variance (Cr) =
VAR FirstDateInContext =
    CALCULATE ( MIN ( 'SalesData'[Date] ), ALLSELECTED ( 'SalesData' ) )
RETURN
    CALCULATE (
        [Total Target] - [Total Actual Sales],
        FILTER (
            ALLSELECTED ( 'DateTable' ),
            'DateTable'[Date] >= FirstDateInContext
                && 'DateTable'[Date] <= MAX ( 'DateTable'[Date] )
        )
    )

Finally, the Corrected Target measure can be created. This formula calculates the Variance (Cr) from the previous month and adds it to the current month's Total Target. It uses the DATEADD function to shift the calculation context back one month. The COALESCE function is important for handling the very first period, ensuring that a missing previous month's variance is treated as zero.

Corrected Target (Cr) =
VAR PreviousMonthVariance =
    CALCULATE (
        [Variance (Cr)],
        DATEADD ( 'DateTable'[Date], -1, MONTH )
    )
RETURN
    IF (
        NOT ISBLANK ( [Total Target] ),
        [Total Target] + COALESCE ( PreviousMonthVariance, 0 )
    )

To display the results, you can use a Matrix visual in your Power BI report. Place fields like Sales Person Name, Particular, and YearMonth from the DateTable onto the rows. Then, add your measures—Total Target, Total Actual Sales, Corrected Target (Cr), and Variance (Cr)—to the values area to generate the final table.

 

Best regards,

 

tharunkumarRTK
Super User
Super User

@mail2rohitnagar 

You can calcuate previous month value in many ways.

1. PREVIOUSMONTH DAX function - https://dax.guide/previousmonth/

2. Window functions - https://www.sqlbi.com/articles/introducing-window-functions-in-dax/

3. PREVIOUS visual calculation https://dax.guide/previous/

 

It could be difficult for anyone to suggest you the formula without knowing the data model and schema. For further help please share the pbix file with sample data.

 

 

 

 

 

Connect on LinkedIn

 

 

 








Did I answer your question? Mark my post as a solution!
If I helped you, click on the Thumbs Up to give Kudos.

Proud to be a Super User!


PBI_SuperUser_Rank@2x.png

 

Helpful resources

Announcements
July 2025 community update carousel

Fabric Community Update - July 2025

Find out what's new and trending in the Fabric community.

July PBI25 Carousel

Power BI Monthly Update - July 2025

Check out the July 2025 Power BI update to learn about new features.

Top Solution Authors