Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate sum of column value in linq to sql query?

I'm write this query:

var query2 = (from p in behzad.Compare_closed_numbers_in_CRM_and_Billing_system_detail_counters
               where p.fileid == point.id
               select new
               {
                   p.count
               }).ToArray();

in count column have any value,and I want to sum all of the count value. For example: enter image description here

how can I implant that?thanks.

like image 582
behzad razzaqi Avatar asked Sep 05 '15 11:09

behzad razzaqi


People also ask

How do you get the total SUM of a column in SQL?

AVG() SyntaxThe SUM() function returns the total sum of a numeric column.

How do you SUM two columns in LINQ?

Items select new { Sum(p. Total), Sum(p. Done)};

What does include () do in LINQ?

Introduction to LINQ Include. LINQ include helps out to include the related entities which loaded from the database. It allows retrieving the similar entities to be read from database in a same query. LINQ Include() which point towards similar entities must read from the database to get in a single query.


1 Answers

If count field is int try this:

int sum = behzad.Compare_closed_numbers_in_CRM_and_Billing_system_detail_counters
     .Where(t=>t.fileid == point.id)
     .Select(t => t.Count ?? 0).Sum();

If count field is nvarchar(max) try this:

int sum = behzad.Compare_closed_numbers_in_CRM_and_Billing_system_detail_counters
         .Where(t=>t.fileid == point.id)
         .Select(t => Convert.ToInt32(t.Count)).Sum();
like image 130
Salah Akbari Avatar answered Oct 12 '22 03:10

Salah Akbari