Sum product costs with same ID in Power Query - powerbi

I have multiple rows with same ID but different products/prices. I would like to get this in Power Query (PowerBI) due to the automation.
Excel formula looks like this:
=SUMPRODUCT(IF($A$2:$A$7=A2;$B$2:$B$7))
And the table is:
A (ID)
B (price)
1
10
1
20
1
5
2
3
2
6
2
1
My goal is to get this:
C (Formula-price)
35
35
35
10
10
10
This step represent Column P & Q (Claims List) in this sheet: https://docs.google.com/spreadsheets/d/1J_nl2_Dgam7JDdyzX-urrO2AEXuCzhQkB1nogTLn2eA/edit#gid=0

In powerquery, right click and group on ID. Add a sum of one of the number columns and then below that, choose All rows as the operation.
After grouping use arrows atop the new column to expand the other columns
Sample, without the expansion
let Source = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}, {"Column2", Int64.Type}, {"Column3", Int64.Type}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"Column1"}, {{"Count", each List.Sum([Column2]), type nullable number}, {"data", each _, type table }})
in #"Grouped Rows"

So I am guessing a little bit but I think you would like to add the sum of B(price) grouped by A(id) to every row in your table. And you would like to use Powerquery for that.
First step would be to import the table into powerquery, then I duplicate the query and group it by ID. The third step is to merge these table by ID
Step 1
I took the following example data
Goto Data/From Table/Range and you should get
Step2 Right click on the query above and select Duplicate
I named the result sumTbl , grouped it by ID and with price as the column to sum
PS In the above step you can change to Advanced and add a second aggreagtion level and then expand. No need to merge!
The result looks like
Step 3 Now you merge both tables. I merged them as a new one
The result is
Now you only need to expand the column sumTbl
The result will be

Related

Power BI Store product of previous row subtracting from another column into the next row

Current Setup
CntrlRunTot is a hardcoded column of values. I'm trying to make a calculated column that subtracts its previous row from the demand qty that corresponds to its row and have that product stored in the row below. Ex. 188535 - 2976 = 185559 which is then stored a row beneath the 188535 row. Right now my Running Total calculated column depends on every value of CntrlRunTot but I need it to just depend on that first number 188535 and then be able to subtract Demand Qty and store the following values within its consecutive rows.
You can do that by editing the Query (Home=>Transform to get to the query editor from Power BI).
I use the List.Generate function to generate a list of the Running Totals; then combine that column with the rest of the table
M Code
let
//Change next two lines to whatever your data source really is
Source = Excel.CurrentWorkbook(){[Name="Table11"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{
{"Demand Qty", Int64.Type}, {"ContrlRunTot", Int64.Type}, {"Index", Int64.Type}}),
//Add running total column
// Change Table.ToColumns argument to the correct reference
#"Add Running Total" = Table.FromColumns(
Table.ToColumns(#"Changed Type") &
{List.Generate(
()=>[rt=#"Changed Type"[ContrlRunTot]{0}, idx=0],
each [idx] < Table.RowCount(#"Changed Type"),
each [rt = [rt] - #"Changed Type"[Demand Qty]{[idx]+1}, idx=[idx]+1],
each [rt])},
type table[Demand Qty=Int64.Type, ContrlRunTot=Int64.Type, Index=Int64.Type, Running Total=Int64.Type])
in
#"Add Running Total"

Power BI Grouping

Location
Won
Lost
Home
3
4
Home
2
3
Home
5
4
Home
4
6
Away
3
4
Away
2
3
Away
5
4
Away
4
6
This is an example table that I have in Power BI. I am trying to create a new table, that groups by Location, sums up the values of won and lost, and adds a third column that has the ratio of sum(won)/sum(lost) called Ratio. So all in all, you have three columns: Location (either home or away), Wins (sum of wins), Lost (sum of lost), ratio (the result of dividing wins and lost, the previous two columns)
How can I write the formula I need in Power BI?
There is a function for that called SUMMARIZE, see docs
May be like:
SUMMARIZE(your_table
, your_table[Location]
, "Total Won", SUM(your_table[Won])
, "Total Lost", SUM(your_table[Lost])
, "Ratio", SUM(your_table[Won]/your_table[Lost])
)
You can also create this using Power Query.
Your existing table is produce by a query named myTable
In Power BI Desktop, select `Queries => Transform"
In the PQ UI, select Home=>Advanced Editor and paste the code below into the window that opens.
You may need to change the name in the second line from myTable to whatever that query is really named
I use the Table.Group function to do the appropriate calculations on each grouped sub-table
M Code
let
Source = myTable,
//Group by Location, then add the columns
#"Grouped Rows" = Table.Group(myTable, {"Location"}, {
{"Wins", each List.Sum([Won]), type nullable number},
{"Losses", each List.Sum([Lost]), type nullable number},
{"Ratio", each List.Sum([Won])/List.Sum([Lost]), type number}
})
in
#"Grouped Rows"
Results from your data above

Power BI - How to display only the values which appear more than once in a column

I have a table with multiple columns. One of these is 'EAN'. In this column there are supposed to be unique values. Unfortunatly this is not the case. Now I want to find all the values that appear more then once.
I tried the FILTER, EARLIER, COUNTROWS. Nothing gives the output I'm looking for.
Example:
Art A - 111
Art B - 123
Art C - 222
Art D - 222
Art E - 456
What I expect as output is just a table, column or chart where '222' appears.
Create your visual using the EAN field.
Then create a measure with the formula:
= COUNTROWS('Table')
and drag this measure into the filters pane, setting the condition to 'greater than 1'.
Here's one way just using Power Query and M Code:
let
//read in and type the data
Source = Excel.CurrentWorkbook(){[Name="Table8"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Art", type text}, {"Num", Int64.Type}}),
//selectd only those rows where there are at least two identical nums
filter = Table.SelectRows(#"Changed Type", each List.Count(List.Select(#"Changed Type"[Num], (li)=>li=[Num]))>1),
//sort the output to keep the duplicates together
#"Sorted Rows" = Table.Sort(filter,{{"Num", Order.Ascending}})
in
#"Sorted Rows"

In Power Query, how to replace values in multiple columns with values in another table?

I'm working with the American Community Survey in Power BI and want to replace values in every column with corresponding values in another table of response labels. For example, race is encoded as 1,2,3,4,5 but I want to replace it with Asian, Black, Native, etc according to the response labels provided.
Let's say I have the following table with three variables and peoples' responses:
variable1
variable2
variable3
1
2
3
2
3
2
3
1
1
3
3
2
2
2
3
I am provided with this table of response keys:
VarName
ResponseKey
ResponseLabel
variable1
1
blue
variable1
2
red
variable1
3
green
variable2
1
left
variable2
2
right
variable2
3
down
variable3
1
high
variable3
2
medium
variable3
3
low
What I want is those three variables with the peoples' responses as the 'ResponseLabel' like so:
variable1
variable2
variable3
blue
right
low
red
down
medium
green
left
high
green
down
medium
red
right
low
Usually I would go one by one and replace each variable by hand but I would rather have a root canal than do that for hundred plus variables with anywhere from 2-100 responses so I imagine there is a better way to do this.
So far, I've thought about making tables for each variable and merge with the original table but that sounds like a lot as well. Then I thought maybe I should write a function to iterate across the original table and recode each column one by one. I'm also thinking there might be a way to do this in M but I'm not sure.
Do you have any ideas?
Thanks!
Assume your Response Keys table is Table1 and loaded into Powerquery
For the top table, load into PowerQuery
Add column ... index column ...
Right click new index column and ... Unpivot other columns ...
Home .. Merge Queries ...
Set bottom table to Table1, and click to match Attribute with VarName and Value with ResponseKey, with left outer join
Click the arrows atop the new column and [x] expand ResponseLabel
Right click value column and Remove
Click select attribute column, then Transform .. pivot columns ... value = ResponseLabel and Advanced=dont aggregate
Right click index column and Remove
Done
Full code:
let Source = Excel.CurrentWorkbook(){[Name="Table2"]}[Content],
#"Added Index" = Table.AddIndexColumn(Source, "Index", 0, 1),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Added Index", {"Index"}, "Attribute", "Value"),
#"Merged Queries" = Table.NestedJoin(#"Unpivoted Other Columns",{"Attribute", "Value"},Table1,{"VarName", "ResponseKey"},"Table1",JoinKind.LeftOuter),
#"Expanded Table1" = Table.ExpandTableColumn(#"Merged Queries", "Table1", {"ResponseLabel"}, {"ResponseLabel"}),
#"Removed Columns" = Table.RemoveColumns(#"Expanded Table1",{"Value"}),
#"Pivoted Column" = Table.Pivot(#"Removed Columns", List.Distinct(#"Removed Columns"[Attribute]), "Attribute", "ResponseLabel"),
#"Removed Columns1" = Table.RemoveColumns(#"Pivoted Column",{"Index"})
in #"Removed Columns1"

Using Powerquery to link reference table to column headers of data table to create averages

I have a data table, that contains survey data with the following column headers:
Answerid | Question 1 | Question 2 | Question 3
1 3 4 5
And a reference table that links question categories to the questions:
Question 1 | Category A
Question 2 | Category B
Question 3 | Category B
Now I would like to view results as averages on a Category level. For example in a bar chart where each bar shows the average value for that category.
Load in reference range with no column headers and call it Reference. Load in data table. Right click first column, choose Unpivot other columns. Home...Merge Queries... Merge to table Reference and click on Question column at top and bottom to link them. Expand results by clicking arrow box at top of new column. Right click column with Category, Group By, use average and apply to the column with numerical field. Add your own chart as desired
let Source = Excel.CurrentWorkbook(){[Name="Table2"]}[Content],
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"AnswerID"}, "Attribute", "Value"),
#"Merged Queries" = Table.NestedJoin(#"Unpivoted Other Columns",{"Attribute"},Reference,{"Column1"},"RefernceTable",JoinKind.LeftOuter),
#"Expanded RefernceTable" = Table.ExpandTableColumn(#"Merged Queries", "RefernceTable", {"Column2"}, {"Column2"}),
#"Grouped Rows" = Table.Group(#"Expanded RefernceTable", {"Column2"}, {{"Average", each List.Average([Value]), type number}})
in #"Grouped Rows"