问题
I'm struggling to pass column names to a power query function - if I pass them as [columnname] within the function call, it tries to implement them outside the function; if I pass using [parameter] within the function itself, it looks for a column "parameter" and not the column name that's passed in the call.
Elsewhere, StackExchange recommends using Table.Column(table,columnname) to get around this, but the I get the whole column in one go, rather than being able to compare corresponding entries within the column.
Can anyone help? Here's the code
(table,Mt0,Mt1) => let
#"Add Yt.1" = Table.AddColumn(table, "placeholder",
each if Table.Column(table,Mt0) <= 0 or - Table.Column(table,Mt1) < Table.Column(table,Mt0)
then Table.FromRecords({[Mt0 = Table.Column(table,Mt0), Mt1 = Table.Column(table,Mt1)]})
else Table.FromRecords({[Mt0 = 0,Mt1 = Table.Column(table,Mt1) + Table.Column(table,Mt0)]}))/*,
#"Expand Yt.1" = Table.ExpandTableColumn(Table.RemoveColumns(#"Add Yt.1",{"Mt0", "Mt1"}), "placeholder", {"Mt0","Mt1"})*/
in #"Add Yt.1"
This is stored as Query1 and I'm calling using Query1(tablename,Y1M,Y2M)
This version generates an error: We cannot apply operator "<=" to types List and Number (so while it may be referencing column Y1M as intended, it's comparing the whole column (as a list) to '0' in the first inequality, rather than one entry at a time.
Help!!
回答1:
Try using Record.Field(_, Mt0)
instead of Table.Column
回答2:
This was very helpful. This was making me a little nuts. Code that doesn't work followed by one that does.
This does not work
(tablename as table, columnname as text)=>
let
// results in new column with all values null
Source = tablename,
GetColumn = Table.AddColumn(Source, "Text", each ```Text.Middle(columnname, 32, 7 ) , type text)
in
GetColumn
This does work, using (Record.Field(_, columnname)
)
(tablename as table, columnname as text)=>
let
results in new column with characters properly ```extracted from the column specified with ```columnname when invoking the function
Source = tablename,
GetColumn = Table.AddColumn(Source, "Text",
each Text.Middle(Record.Field(_, columnname), 32, 7), type text)
in
GetColumn
Thank you!
来源:https://stackoverflow.com/questions/55840125/power-query-pass-column-name-as-function-parameter