How do I calculate Sum of two rows in DataTable which is of type string ?
in my case I cannot change column type.
I tried these :
1)
object objSum;
objSum = dt.Compute("Sum(WeightRate)", "");
2)
decimal total = (decimal)dt.Compute("SUM( [WeightRate] )", "");`
But no luck...
My table :
Weightrate No.Ofvehicles
350.50 50
205.00 40
I need result as
Weightrate No.Ofvehicle
555.50 90
The Compute method allows for some rudimentary type conversion:
var sum = dt.Compute("Sum(Convert(WeightRate, 'System.Int32'))");
See the MSDN help on DataColumn Expressions for more information about what you can do with a Compute method call.
Edit Having re-read your question, you'll probably want to convert to System.Decimal rather than System.Int32, but hopefully you got that. ;-)
Fixed it by using the below:
var result = dt.AsEnumerable().Sum(x => Convert.ToInt32(x["WeightRate"]));
Related
I have a list of data with a title column (among many other columns) and I have a Power BI parameter that has, for example, a value of "a,b,c". What I want to do is loop through the parameter's values and remove any rows that begin with those characters.
For example:
Title
a
b
c
d
Should become
Title
d
This comma separated list could have one value or it could have twenty. I know that I can turn the parameter into a list by using
parameterList = Text.Split(<parameter-name>,",")
but then I am unsure how to continue to use that to filter on. For one value I would just use
#"Filtered Rows" = Table.SelectRows(#"Table", each Text.StartsWith([key], <value-to-filter-on>))
but that only allows one value.
EDIT: I may have worded my original question poorly. The comma separated values in the parameterList can be any number of characters (e.g.: a,abcd,foo,bar) and I want to see if the value in [key] starts with that string of characters.
Try using List.Contains to check whether the starting character is in the parameter list.
each List.Contains(parameterList, Text.Start([key], 1)
Edit: Since you've changed the requirement, try this:
Table.SelectRows(
#"Table",
(C) => not List.AnyTrue(
List.Transform(
parameterList,
each Text.StartsWith(C[key], _)
)
)
)
For each row, this transforms the parameterList into a list of true/false values by checking if the current key starts with each text string in the list. If any are true, then List.AnyTrue returns true and we choose not to select that row.
Since you want to filter out all the values from the parameter, you can use something like:
= Table.SelectRows(#"Changed Type", each List.Contains(Parameter1,Text.Start([Title],1))=false)
Another way to do this would be to create a custom column in the table, which has the first character of title:
= Table.AddColumn(#"Changed Type", "FirstChar", each Text.Start([Title],1))
and then use this field in the filter step:
= Table.SelectRows(#"Added Custom", each List.Contains(Parameter1,[FirstChar])=false)
I tested this with a small sample set and it seems to be running fine. You can test both and see if it helps with the performance. If you are still facing performance issues, it would probably be easier if you can share the pbix file.
This seems to work fairly well:
= List.Select(Source[Title], each Text.Contains(Parameter1,Text.Start(_,1))=false)
Replace Source with the name of your table and Parameter1 with the name of your Parameter.
I understand ? is used to access data, such as column in Frame, but the returned column will be in float.
How about assignment of new column in a Frame?
let second = Series.ofValues(["d";"e";"f"])
let df?second = second
I tested this new column will stay as string, actually, I just would like to know if there is a place that systematically explain the use of ? operator.
Think maybe that https://github.com/BlueMountainCapital/Deedle/blob/master/docs/content/frame.fsx from line 231 and downwards gives some explanations on how to use it.
It does not explain other hows or whys, but might be what you need or want...
i have a model Timer(id:integer, track:string, time_point:integer)
before this question i asked on stackoverflow about reorganizing my array with integer values to array with ranges and took a pretty nice answer(biggest thanks for steenslag):
array = [1,4,10,14,22]
array.unshift(-1)
ranges = array.each_cons(2).map{|a,b| a+1..b} #=>[0..1, 2..4, 5..10, 11..14, 15..22]
array.shift
now i want to apply this solution and create an integer array with all my time_points for next reorganizing. how could i get this array?
thanks for help
You can use #pluck method to get all the column values as an Array.
time_points = Time.pluck(:time_point)
I have the following sample code. The objective is to run SQL statement with multiple input parameters.
[<Literal>]
let connectionString = #"Data Source=Localhost;Initial Catalog=Instrument;Integrated Security=True"
[<Literal>]
let query = "SELECT MacroName, MacroCode FROM Instrument WHERE MacroCode IN (#codeName)"
type MacroQuery = SqlCommandProvider<query, connectionString>
let cmd = new MacroQuery()
let res = cmd.AsyncExecute(codeName= [|"CPI";"GDP"|]) |> Async.RunSynchronously
However, codeName is inferred to be string type instead of an array or list and give me an error.
Alternatively, I could run the query without where statement and filter based on the result. However, in lots of other cases that returns millions of rows, I would prefer filter data at the SQL server level to be more efficient.
I didn't find any relevant samples on the documentation of fsharp.data.sqlclient. Please help!
"See Table-valued parameters (TVPs)" section in the documentation:
http://fsprojects.github.io/FSharp.Data.SqlClient/configuration%20and%20input.html
If you have an upper bound n on the values in the IN list, you could just make n parameters. If that's unmanageable, I'm afraid the TVP suggestion is your best option. The reason the FSharp.Data.SqlClient library is unlikely to ever support this directly is because the types are generated based on results from sp_describe_undeclared_parameters; there's no T-SQL parser. We had a single digit upper bound in this scenario and were loathe to change the database, so this option worked for us.
You can use STRING_SPLIT to abstract away the use of table-valued parameters. It seems you have to also declare the param first.
DECLARE #param varchar(1000) = #commaSeparatedList
SELECT Col1 FROM MyTable
WHERE Col2 IN (
SELECT value FROM STRING_SPLIT(#param, ',')
)
I am a brand new to F#, and I am having trouble with a simple first query. I have a data set, and I want to group the dollar amount based on the codes (which repeat in the data). Then, for each group I want the average (and eventually standard deviation) of the dollar amounts for each group. Also, I only want to look at ONE providerID, hence the 'where' clause. From my research, I have gotten this far:
let dc = new TypedDataContext()
let query2 = query { for x in dc.MyData do
groupBy x.Code into g
where (x.ProviderId = "some number of type string")
let average = query { for n in g do
averageBy n.DollarAmt }
select (g.Key, average) }
System.Console.WriteLine(query2)
With this I get a compiling error that says, "The namespace or module 'x' is not defined."
I do not understand this because when I ran the query that only collected the data with the specified providerID, it did not complain about this 'x', and I followed the same format with this 'x' for this larger query.
Any ideas? Thank you in advance.
From #kvb's comment: After the groupBy you can only access the group g, not the individual items x. Try putting the where before the groupBy.