Power Query (M) _ Dynamically update a column list for List.Sum function - excel

I'm not sure if even possible but the goal is to dynamically update a query based on the user selecting a date. I have a table in my Excel file while updates a value which feeds to PeriodString variable (below)
/*Parameter name = PeriodString */
let
Source = Excel.CurrentWorkbook(){[Name="PeriodString"]}[Content],
StrPeriod = Source[Value]{0}
in
StrPeriod
The part of the code I want to update is the [ ..months selected ].
=List.Sum({[FYOpening],[January],[February],[March],[April],[May]})
With the below variable
=List.Sum({PeriodStr})
I tried using Table.Column as I realize I have to convert the value to a list of selectable columns but I cant' get it to work.
=List.Sum({Table.Column(PeriodString{0},PeriodString[0])})
Expression.Error: We cannot convert the value "[FY Opening],[Januar..." to type List.
Details:
Value=[FY Opening],[January],[February],[March],[April],[May]
Type=[Type]
Let me know if possible / alternatives.

If you need exactly value like "[Col1],[Col2],[Col3]" for PeriodString, then use such code:
let
Source = #table({"a".."e"},{{1..5}, {6..10}}),
PeriodString = "[b],[d],[e]",
sum = Table.AddColumn(Source, "sum", each List.Sum(Expression.Evaluate("{"&PeriodString&"}", [_=_])))
in
sum
I'd prefer to use PQ list instead:
let
Source = #table({"a".."e"},{{1..5}, {6..10}}),
list = {"b","d","e"},
sum = Table.AddColumn(Source, "sum", each List.Sum(Record.ToList(Record.SelectFields(_, list))))
in
sum

Related

Filter leading to different results when typed manually and via defined as a variable

I'm trying to create a calculated column indicating if a team has a prize or not from the table below:
To do that I need to count within the group if there's a player whose "Prize" field is not empty. Here's the 1st attempt:
Dax Formula:
=
Var Player_Same_Team = filter(Table4,Table4[Team]=earlier(Table4[Team]))
Var Has_Prize = len(Table4[Prize])>0
Return
calculate(countrows(filter(Table4,len(Table4[Prize])>0)),Player_Same_Team)>0
Looks like it's going what I intend it to do. However, when I swap the filter content to a pre-defined variable, it gave me results that don't make sense:
Dax Formula:
=
Var Player_Same_Team = filter(Table4,Table4[Team]=earlier(Table4[Team]))
Var Has_Prize = len(Table4[Prize])>0
Return
calculate(countrows(filter(Table4,Has_Prize)),Player_Same_Team)>0
The typed content len(Table4[Prize])>0 is the same as that in the variable, so what may be causing the difference? Thanks for your help.
As soon as you assign it to a variable, the value of the variable remains constant. Therefore the Len is evaluated to a value, that you are then passing as a filter.
The first example works because the CALCULATE accepts a table as a parameter, and player_same_team is evaluated to a table, by using the FILTER expression.
In order for what you are trying to do to work it would have to be something like this:
= Var Player_Same_Team = filter(Table4,Table4[Team]=earlier(Table4[Team]))
Var Has_Prize = filter(Table4,len(Table4[Prize])>0)
Return calculate(countrows(Has_Prize),Player_Same_Team)>0
You can also write the measure in a slightly different way:
= CALCULATE ( COUNT(Table4[Team]),
ALLEXCEPT(Table4[Team]),
LEN(Table4[Prize])>0) > 0

Find matching value in query based on text

I am building a table in power query and I want to find the matching value from a column in a row. Does anyone know how to do this? I import my source data with:
leagueDataSource = #"League Data All",
this gives me this table:
I then have a variable called:
leagueName = "Albania - Superliga",
and want to create another variable called activeSeason. How do I match the variable leagueName with the value in active Season ?
Found the answer myself :)
leagueName = "name",
a = List.PositionOf(leagueDataSource[League], leagueName, 0),
leagueID = Number.ToText(leagueDataSource[Active Season]{a}),

How to use variable column name in a function for other functions?

I have written two functions which take date as input and I'm gonna use them on multiple queries. Instead of doing manual work every time (call both functions, filter rows where first function returns True, expand record of the second function to columns, delete first function column) I thought I'd write another function that takes names of the table and the column with dates as parameters to automatize that process. My current table-based function works if I include specific column's date in the code, but those names will be different between different queries(tables).
Here's the table function's code:
(t as table) =>
let
FunctionFilter = Table.AddColumn(t, "DateFilter", each DateFilter([myDate2])),
FunctionPeriods = Table.AddColumn(#"FunctionFilter", "TimePeriods", each TimePeriods([myDate2])),
ExpandPeriods= Table.ExpandRecordColumn(FunctionPeriods, "TimePeriods", {"Year", "Quarter", "Month", "WeekMon", "WeekTue", "Day"},
{"Year", "Quarter", "Month", "WeekMon", "WeekTue", "Day"}),
TrueDate = Table.SelectRows(ExpandPeriods, each ([DateFilter] = true)),
DeleteDateFilter = Table.RemoveColumns(TrueDate,{"DateFilter"})
in
DeleteDateFilter
My only problem is inserting a variable column name in place of [myDate2] here:
FunctionFilter = Table.AddColumn(t, "DateFilter", each DateFilter([myDate2])),
FunctionPeriods = Table.AddColumn(#"FunctionFilter", "TimePeriods", each TimePeriods([myDate2])),
Using Table.Column(t,[column name]) returns a list instead of a date, which causes called date functions to throw a type mismatch error.
You may use such technique:
// Table
let
Source = #table(3,List.Zip({{"a".."d"},{1..4},List.Numbers(10,4,10)})),
fn = fn(Source, "Column3")
in
fn
// fn
(tbl as table, col as text) =>
let
i = Table.AddIndexColumn(tbl, "i", 0, 1),
add = Table.AddColumn(i, "new", each Table.Column(i, col){[i]}*10),
del = Table.RemoveColumns(add, "i")
in
del

Trying to pull data from a SODA API into Excel

The API call looks like this:
https://data.edmonton.ca/resource/3pdp-qp95.json?house_number=10008&street_name=103%20STREET%20NW
and returns data in json:
[{"account_number":"3070208","garage":"N","house_number":"10008","latitude":"53.539158992619","longitude":"-113.497760691896","neighbourhood":"DOWNTOWN","street_name":"103 STREET NW","tax_class":"Non Residential","total_asmt":"1717000"}]
I have an excel table with specific house_number and street_name pairs and I want to capture the total_asmt column for each pair.
I've been able to create a power query which pulls the very first data point into a new sheet:
let
Parameter = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Removed Other Columns" = Table.SelectColumns(Parameter,{"house_number", "street_name"}),
X = #"Removed Other Columns"[house_number]{0},
Y = #"Removed Other Columns"[street_name]{0},
Source = Json.Document(Web.Contents("https://data.edmonton.ca/resource/3pdp-qp95.json?house_number="& X &"&street_name=" & Y)),
in
Source
I can't figure out how to iterate through all the value I have in X and Y or how to capture specific rows from the JSON data. Any help would be appreciated!
Thanks,
Aaleem
I think your best best is to not do it.
Why are you wasting your time scraping this data one address at a time when you could have the entire city's data in under a minute.
JSON: https://data.edmonton.ca/resource/3pdp-qp95.json
CSV: https://data.edmonton.ca/api/views/q7d6-ambg/rows.csv?accessType=DOWNLOAD
XML: https://data.edmonton.ca/api/views/q7d6-ambg/rows.xml?accessType=DOWNLOAD
...among others. Heck, they even have !
And when you're done with that one, they have a few hundred other interesting datasets.
The trick was to create a function inside powerquery, and then use the query as part of a table. Create the function as below and then under the data tab select your table using "From Table/Range" from there it is pretty straight forward.
let a_value= (x as number,y as text)=> //this creates the function
let //this is essentially the query I wanted with some minor changes from above
x_text = Number.ToText(x, "D", ""),
Source = Json.Document(Web.Contents("https://data.edmonton.ca/resource/3pdp-qp95.json?house_number="&x_text&"&street_name="&y)),
Source1 = Source{0},
total_asmt = Source1[total_asmt]
in
total_asmt
in a_value //closes the function

Creating an associative array using a while loop for select list?

I am dynamically generating a selectlist in Drupal and I want to create an associative array to populate the node ID as the value, and the title of the node as the option.
By default, it makes the value for each option the index of the select list. This is no good because the select list is dynamic, meaning the values won't be in the same order.
I used drupal_map_assoc to make the value the same as the option, but I have queries based on the value stored in this field, so if someone updates the value stored, the queries won't match.
<option value="Addison Reserve Country Club Inc.">Addison Reserve Country Club Inc.</option>
I want to replace the value with the Node ID also pulled with the query.
$sql = 'SELECT DISTINCT title, nid FROM {node} WHERE type = \'accounts\' ';
$result = db_query($sql);
while ($row = db_fetch_array($result)) {
$return[] = $row['title'];
//Trying to do something like 'Addison Reserve Country Club' => '2033' - where 2033 is the nid
}
$return = drupal_map_assoc($return);
I think you just want to do this inside the loop:
$return[$row['nid']] = $row['title'];
Based on your comment, you would also want to do an array_flip() right after the loop, but I think your comment may just have it backwards.

Resources