powerbipowerquery

Power BI Reference values in column as the headers of another table


I have a table that looks like the one below with types X, Y, Z.

Table 1

X Y Z
1 1 0
0 4 0

In simple terms, I want to create a new table in Power Query for a visual that will look something like this to count (not sum) non-zero rows. Once I can get the base count functional, I will add more columns with other filters for counts.

Table 2

Type Total
X 1
Y 2
Z 0

I have tried transposing the headers into a column (Type) then creating a calculated column (Total) that will reference the value in "Type" and count the rows of the corresponding column in Table 1. I'm sure there is a way but I can't get the syntax right. My base function in Power Query is:

= Table.AddColumn(#"Added Column", "Total", each List.NonNullCount(#"Table 1"[#"Table 2"[Type]]))

That is obviously wrong but it shows basically what I'm trying to put in the List.NonNullCount. I have tried various reference methods within that function but I either get errors or in-correct results.

I also turning the reference headers into a list and trying to iterate with that but no luck.

I need the reference to be dynamic and not static X,Y,or Z. The source table is A-Z and X,Y,Z is only what is filtered out. If needs change, the filter table may be A,B,C,Z instead. I'm also open to suggestions for other ways to show my end result. This seems fairly straightforward but other answers I've looked up seem to have enough differences that it doesn't work for me.


Solution

  • You can try

    let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Demoted Headers" = Table.DemoteHeaders(Source),
    #"Transposed Table" = Table.Transpose(#"Demoted Headers"),
    #"Added Custom" = Table.AddColumn(#"Transposed Table", "Total", each List.Sum(List.Transform(Record.ToList(_),each if _=0 then 0 else 1))-1),
    #"Removed Other Columns" = Table.SelectColumns(#"Added Custom",{"Column1","Total"})
    in #"Removed Other Columns"
    

    It moves the column titles to row 1, then flips sideways. Record.ToList(_) will give all the rows of that row. Use an if formula to check if each item in list is 0 or not. Sum that and subtract one since the title also is counted

    enter image description here

    note code above is pasted into home ... advanced editor....

    change the Record.ToList(_) to List.RemoveNulls(Record.ToList(_)) to get rid of any problem with nulls