Simple math on SQL query results or on a datatable - c#

Let's say I have a query that returns something simple like...
**TYPE** **TOTAL**
A 2
B 4
And I want to do some math like A/(A+B) -> 2/(2+4) then display that on my website. Is that more feasible to do within the query or after when I have it stored in a datatable??

Just try something like this if you realy need to get it done in same way.
SELECT A/(A+B) FROM((SELECT total as A FROM TB WHERE type='A' LIMIT 1),(SELECT total as B FROM TB WHERE type='B' LIMIT 1))
Tested and working..

Related

How to aggregate sum in sqlite Xamarin to get a total count?

I have a feature class which contain property information, what I would like to do it total the value of all properties and display that in a table. The attribute table looks something like this:
ObjectId PID Value
0 1000 10,000
1 1001 25,000
2 1002 100,000
I would like to sum the value field, in order to give me a total for the entire area. So in this example, the value of all properties would be $135,000... I would like to calculate this and display it...
sounds like a pretty straight forward problem, but I can't seem to find a solution. How to do this on Xamarin forms MVVM format
Well, assuming you are using SQL then you would use something like:
select sum(count) from TableXXX where location = 'colombo'.
If you are using EF then it would be more like:
double x = dbContext.DbSet("XXX")
.Where(item => item.Location == "colombo")
.Select(item => item.Count)
.Sum();

Send a cell from table to a variable

I have a table like this:
table1(ID(int),total(int))
What I want to do is I want to send total value from table to a variable I made in C# using LINQ something like this:
int a;
a=table1.total();
Now I know this is wrong, pretty sure we have nothing of this sort in C# but I need something like that, because I wanna use this variable in another place. I have tried bringing it straight from table but it doesn't work at all.
ok so this is how i did it
DataClasses1DataContext db = new DataClasses1DataContext();
table1 b = (from r in db.table1
where row.id == 1
select r).FirstOrDefault();
int a;
a=convert.toint32(b.total);
that pretty much did what i wanted now the variable a has the value of total from table1 and i can use it on other parts of program
thank you for taking the time to look at my question.

calculate total of rows all in the same column in sql database

I have a sql table called expenses with an int column called cost. In my application this data is displayed on a grid which is refreshing every time I insert a new row with a linq2sql insert. What I would like to do is have an integer variable in my application that is the sum of all the fields in the cost column every time I insert a row.
Is there a simple way to sum these fields with linq2sql every time I do an insert. Please try to avoid lambda as I haven't gotten to learning that yet.
Thanks!
Assuming that you use query syntax instead of lambdas, here you are:
var totalCost = (from expensesRow in dataContext.Expenses
select expensesRow.cost)
.Sum();
Which in fact is the same as:
var totalCost = dataContext.Expenses
.Sum(x => x.cost);
Here dataContext is an instance of your Linq2Sql DataContext class.
You get to learn lambdas today. http://www.theabsentmindedcoder.com/2010/06/linq-sum.html has exactly what you want, and uses a very simple lambda to get there. You could get away without the lambda by making your select gather up only the one column of integers you're trying to sum, but why do extra work to not learn things?
Say I had a table called users with the following structure:
[Table users] - id | username | points_awarded
Then, I can find the total number of points I awarded every user by running the query:
SELECT SUM(points_awarded) as total_points FROM users
You can also count how many users have points greater than our equal to N. For example, says N = 500, then I can run:
SELECT COUNT(id) as num_users_with_points FROM users WHERE points_award >= 500
Check out:
http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
http://dev.mysql.com/doc/refman/5.0/en/func-op-summary-ref.html
for more information.

NHibernate - How do I use a sum project on paged results

I'm trying to use paging in conjunction with a sum projection to get a sum of the values in a column for just the page of results I'm interested in. I'm using .NET, C# and NHibernate 3.1
I have an ICriteria to start with which is related to all rows from the associated db table.
I'm then doing the following to get a version with the first page (say, 10 items out of 40):
ICriteria recordsCriteria = CriteriaTransformer.Clone(criteria);
recordsCriteria.SetFirstResult(0);
recordsCriteria.SetMaxResults(10);
I'm using this ICriteria for something else so I then create two further clones:
ICriteria totalAggCriteria = CriteriaTransformer.Clone(criteria);
ICriteria pageAggCriteria = CriteriaTransformer.Clone(recordsCriteria);
If I take a look inside these two new ones the first has 40 items in and the second has 10 - exactly what I want.
Let's say the objects coming back from the DB have a column called "ColA" and it's of type Int32.
From this, I want the sum of all 40 ColA values and the sum of the first 10 ColA values.
To get the sum of all 40 ColA values, I do the following:
totalAggCriteria.SetProjection(NHibernate.Criterion.Projections.Sum("ColA"));
var totalSum = totalAggCriteria.UniqueResult();
The value in totalSum is correct.
To get the sum of the first 10 ColA values, I'm trying the following:
pageAggCriteria.SetProjection(NHibernate.Criterion.Projections.Sum("ColA"));
vat pageSum = pageAddCriteria.UniqueResult();
However, this gives me the same value as the previous one - for all 40 ColA values.
I've also tried the following but it gives the same result:
pageAggCriteria.SetProjection(NHibernate.Criterion.Projections.Sum(column));
pageAggCriteria.SetFirstResult(firstResult.Value);
pageAggCriteria.SetMaxResults(pageSize.Value);
pageSum = pageAggCriteria.UniqueResult();
And also:
pageAggCriteria.SetFirstResult(firstResult.Value);
pageAggCriteria.SetMaxResults(pageSize.Value);
pageAggCriteria.SetProjection(NHibernate.Criterion.Projections.Sum(column));
pageSum = pageAggCriteria.UniqueResult();
Can anyone give an idea on where I'm going wrong and how I can actually get the sum of the ColA values in the first 10 results?
Thanks
Probably easiest to do that sum client side. The aggregate function is operating on the whole table. What you are trying to do is run the aggregate function against the paged result which I don't think is possible with NH.
In other words, you want select sum(colA) from (select top 10 ...) but that criteria will give you select top 10 sum(colA) from ...)

Steps for a beginner to run very basic linq to sql query using Linqpad

Trying to learn Linq using LinqPad and getting frustated with how to start on it. Let's say I want to write a C# Expression and a C# statment where I have a table in SQL server named Products and I want to pull all rows where price is greater then 50. How would yo write it?
Let's say I want to write a C# Expression and a C# statment where I
have a table in SQL server named Products and I want to pull all rows
where price is greater then 50. How would yo write it?
LINQPad builds the typed DataContext for you automatically, so you don't need to instantiate anything. In C# expression mode, just type the folowing:
Products.Where(p => p.Price > 50)
and press F5. Alternatively, you might prefer to use a query expression:
from p in Products
where p.Price > 50
select p
In C# statements mode, you'll need to call the Dump() method to tell it to write out the results. You'll also need to terminate the expression with a semicolon:
Products.Where(p => p.Price > 50).Dump();
There are more examples in the samples section of LINQPad - look at the 5-minute induction.
Just wanted to add - LINQ pad pluralizes - I did not know this and it drove me crazy for a good fifteen minutes
I was trying to select from a table called DentalApplication
DentalApplication.Where(a=> a.PackageID > 0)
Gave me this error
'LINQPad.User.DentalApplication' does not contain a definition for 'Where'
Changed it to
DentalApplications.Where(a=> a.PackageID > 0)
and it worked
var db = new MyDatabaseContext(); // Your database context.
var result = db.Products.Where(q=>q.Price > 50);
...where db represents your ORM context. Price represents your mapping to the Price field in the database. result represents the result set -- your database rows/entities.
Check out: http://msdn.microsoft.com/en-us/library/bb397933(v=vs.90).aspx which will give you an introduction to Linq and using lambda expressions.
Then have a look at http://msdn.microsoft.com/en-us/library/bb386927.aspx which will give you the basics, but to answer your specific question:
var products = db.Products.Where(prod => prod.Price > 50);
foreach(var product in products)
{
//do something
}

Categories