Forum Discussion

Nicks612's avatar
Nicks612
Helper I
1 year ago
Solved

Need help for generating raw wise difference from column using DAX or power query

Hello everyone,

 

Can anyone help me with the below problem?

 

I have attached table named "Raw Data" which contains the Date, Shift, Machine A & Machine B columns. Machine A & Machine B columns has reading of perticular machine stroks that machine has done in entire shift which is always in increasing manner.

 

I want to calculate the difference between two reading of machine A as shown in the table named "Resultant Data". (similar, for the machine B also). then, want two plot a line chart indicating difference A & Difference B with respect to date & shift. 

 

Raw Data:

 

DateShiftMachine AMachine B
5-25-20251st Shift2644159698871
5-26-20252nd Shift2647818699158
5-26-20253rd Shift2651377699249
5-27-20252nd Shift2657855699767
5-27-20253rd Shift2661555700028
5-28-20251st Shift2663637700123
5-27-20251st Shift2663677700325
5-28-20252nd Shift2667838700534
5-28-20253rd Shift2671610700781
5-29-20251st Shift2673756700877

 

Resultant Data:

 

DateShiftMachine ADifference AMachine BDifference B
5-25-20251st Shift26441593659698871287
5-26-20252nd Shift2647818355969915891
5-26-20253rd Shift26513776478699249518
5-27-20252nd Shift26578553700699767261
5-27-20253rd Shift2661555208270002895
5-28-20251st Shift266363740700123202
5-27-20251st Shift26636774161700325209
5-28-20252nd Shift26678383772700534247
5-28-20253rd Shift2671610214670078196
5-29-20251st Shift26737564431700877-700877

 

 

Note A: In resultant column, I have calculated the Difference A & Difference B columns via formula. Please suggest measure & calculated column (both ways) to derived the difference.

 

Note B: for date & shift hierarchy, should I have to go for manual hierarchy or we can add shift in default date hierarchy?

 

Please guide me on this issue. Let me know if you need any further clarification or information.

 

Thanks in Advance!

  • Hi again

     

    Please try ask the right question first time, because it is a bit annoying having to answer twice 😀😀😀

     

    Click here to download a solution ftom one drive

    Click here 

     

    This method will work for 25 machines or more

     

    Please will you now click [thumbs up] and [accept solutoon button].   Thank you !

     

    How it works ...

     

    For the date correctly

    Select the Date and Shift columns, then Transform> Unpiciot>Unpivot other columns

    Sort by Machine, Date and  Shift

    Add an index column from 0 incrementing by 1

    Get the machine and reading for the previous row

     

     

    Change reading to numeric data types
    and add a conditional column

     

     

    Renove the unneeded columns and change the usage ro a numeric data type

     

     

    Draw your graph

     

     

14 Replies

  • Here is M-Code that will calculate the Difference columns, and arrange it in the order you show.

    Paste the code below into the Advanced Editor to see how it works, then adapt it to your actual data.

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("bdBBCgIxDAXQq0jXIzRJk5+ew+UwOxHduNC5P5bWkakd6CLQx+cn8xz0zOVF1jAFeq+ny/1xW8vMlhJpLpNld1BYpoptw/y87jGcvOJM6gOW1x4rCdAwp7xhHCcrXLVhGAbcJxtpxYgx8q+GHy9oYoKGiWVIHjC+WMr3f3Lf2eDiDaukAfedQUax4XLEDefjGhCoNeylz7J8AA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Date = _t, Shift = _t, #"Machine A" = _t, #"Machine B" = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{
            {"Date", type date}, {"Shift", type text}, {"Machine A", Int64.Type}, {"Machine B", Int64.Type}}),
        
        #"Add Differences" = 
            [a=List.Skip(#"Changed Type"[Machine A]),
             b=List.Skip(#"Changed Type"[Machine B]),
             c=List.Zip({a,#"Changed Type"[Machine A]}),
             d=List.Zip({b,#"Changed Type"[Machine B]}),
             e=List.Transform(c, each _{0} - _{1}),
             f=List.Transform(d, each _{0} - _{1}),
             g=Table.FromColumns(
                 Table.ToColumns(#"Changed Type")
                 & {e,f},
                 type table[Date=date, Shift=text,Machine A=Int64.Type,Machine B=Int64.Type,
                            Difference A=Int64.Type, Difference B=Int64.Type])][g],
    
        #"Reordered Columns" = Table.ReorderColumns(#"Add Differences",
            {"Date", "Shift", "Machine A", "Difference A", "Machine B", "Difference B"})
            
    in
        #"Reordered Columns"

    Results from your data:

     

    Just by formatting the Line Chart visual, you can get this:

     

    I don't know how to rotate the x-axis labels on this visual except by making the visual more narrow. I merely used Data and Shift for the x-axis and selected to concatenate the labels.

  • There are lots of ways to solve this problem but try this ...

     

    Click here to download a solution from Onedrive

    Click here 

     

    How it works ...

     

    Change bakue data types to numeric
    Change the date to a proper date.

    Sort by date and shift.

    Add Index colum

    Use the index to get the previous meter reading for A.
    Then use the index to get the previous meter reading for B.
     

    Calculate the usage

    Draw the graph

     

     

    Please click thumbs up because I have tried to help.

     

    Then click [accept solution] if it works.

     

    Many thanks !

     

  • Hey Nicks612 ,

    To calculate the difference in readings (Machine A and Machine B) shift-wise in Power BI using DAX and Power Query, here's a detailed breakdown for both approaches.

    Power Query Steps

    You can sort the data and use the Index method to calculate the difference:

    1. Sort the table:

      • Sort by Date (ascending), then Shift (custom order: 1st Shift, 2nd Shift, 3rd Shift).

    2. Add Index Column:

      • Add an Index column starting from 0.

    3. Duplicate the table:

      • Right-click the query and Duplicate.

    4. Rename duplicated columns:

      • Rename Machine A to Prev Machine A, Machine B to Prev Machine B, and Index to Prev Index.

    5. Merge Queries:

      • Merge the original table with the duplicated one using:

        • Index = Prev Index + 1 (join on: Index from original and Prev Index from duplicate).

    6. Expand columns:

      • Expand Prev Machine A and Prev Machine B.

    7. Add Difference columns:

      Difference A = [Machine A] - [Prev Machine A]
      Difference B = [Machine B] - [Prev Machine B]

     

    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

    • Nicks612's avatar
      Nicks612
      Helper I

      Hi Nasif_Azam & speedramps ,

       

      Thank you for the prompt response. I have tried it and it worked well. Both of you have a similar kind of solution. May many thanks to both of you!

       

      However, I want to know what if there are more than 25 columns and we need this difference for all these columns? It will be tedious to add formula and column for that type of data. So can you please suggest any alternate solution for multiple columns in terms of measure or something?

       

      Thanks in Advance!

      • Nasif_Azam's avatar
        Nasif_Azam
        Super User

        Hey Nicks612 ,

        Glad to hear it worked! And that’s a great follow-up question regarding handling differences across many columns. If you’re dealing with 25+ columns, creating individual formulas for each can be tedious and error-prone. While DAX is powerful for dynamic measures, it isn’t ideal for row-wise comparisons across multiple columns. Instead, I’d suggest sticking with Power Query for scalability.

        Power Query Pattern

        You can automate the difference calculation across all relevant numeric columns using List.Transform and Record.TransformFields.

        1. Sort your data by Date & Shift.

        2. Add an Index Column (Index).

        3. Duplicate the table and shift the index (PrevIndex = Index + 1).

        4. Merge on Index and PrevIndex.

        5. In the Merge step, after expanding the previous row's values:

          • Create a list of target columns (e.g., {"Machine A", "Machine B", ..., "Machine Z"})

          • Then dynamically compute differences:

        let
            columnsToCompare = {"Machine A", "Machine B", "Machine C", ...},
            AddDifferences = Table.TransformColumns(
                MergedTable,
                List.Transform(columnsToCompare, each {
                    "Diff " & _, 
                    each Record.Field(_, _) - Record.Field(_, "Prev." & _), 
                    type number
                })
            )
        in
            AddDifferences

        This will create Diff Machine A, Diff Machine B, etc. for all desired columns without hardcoding each formula.

         

        When creating your line chart combine Date + Shift into a single column for a cleaner X-axis. Like:

        [Date] & " - " & [Shift]

         

        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

  • p45cal's avatar
    p45cal
    Solution Supplier

    In the attached workbook we have:

    • Your source data top left
    • A pivot created from a Power Query transform of your source data
    • A chart of that pivot.

     

     

    You will also notice next to your source data, a column E for a Machine C. This data isn't included in the pivot and chart because it's not currently part of your source data.

    However, dragging the grab-handle bottom right of your data so that column E does become part of the source data table, then refreshing the pivot table yields the following:

     

     

    Note:

    I noticed what appears to be an anomaly with your source data where the dates/shifts seem to be out of order:

    The 1st shift on the 27th May seems to take place after the 1st Shift on the 28th May. Consequently, there's a step in my query which sorts on the stroks count which really shouldn't be there.

  • Hi again

     

    Please try ask the right question first time, because it is a bit annoying having to answer twice 😀😀😀

     

    Click here to download a solution ftom one drive

    Click here 

     

    This method will work for 25 machines or more

     

    Please will you now click [thumbs up] and [accept solutoon button].   Thank you !

     

    How it works ...

     

    For the date correctly

    Select the Date and Shift columns, then Transform> Unpiciot>Unpivot other columns

    Sort by Machine, Date and  Shift

    Add an index column from 0 incrementing by 1

    Get the machine and reading for the previous row

     

     

    Change reading to numeric data types
    and add a conditional column

     

     

    Renove the unneeded columns and change the usage ro a numeric data type

     

     

    Draw your graph

     

     

  • v-venuppu's avatar
    v-venuppu
    Community Support

    Hi Nicks612 ,

    Thank you for reaching out to Microsoft Fabric Community.

    Thank you speedramps Nasif_Azam ronrsnfld p45cal for the prompt response.

    I wanted to check if you had the opportunity to review the information provided.If the response has addressed your query, please accept it as a solution so other members can easily find it.

    Thank you.

  • In the above example I assumed that shift #2 comes after shift #1, but this creates negative usage on the 27/05/2025

     

     

    In this method I have sorted by machine and reading number 

     

     

     

     

    Click here to download from Onedrive

    Click here 

     

    I dont know what sequence you require, but I trust I have taught you the method well enough now
    and that you can change the sort sequence as you require

     

    • Nicks612's avatar
      Nicks612
      Helper I

      Hi speedramps ,

       

      Thank you so much for the support and guidance!

       

      Sorry, for the inconvenience caused and delayed in response as I was not available for some days due to some emergency medical situation...

       

      Thanks a lot!👍