Linq to SQL: Sum with multiple columns select - c#

I want to convert the following SQL code into linq to sql but can't seem to find a way
select holder_name,agent_code,sum(total)
from agent_commission
group by agent_code
Can anyone help me? Am kinda stuck with this for quite a while.
Thanks in advance
UPDATE:
I tried the following
var query = (from p in context.Agent_Commissions
group p by new
{
p.agent_code
}
into s
select new
{
amount = s.Sum(q => q.total),
}
);
How do I select the other two columns? What am I missing?

In fact your SQL query works only when the corresponding relationship between holder_name and agent_code is 1-1, otherwise the Group by agent_code won't work. So your linq query should be like this:
var query = from p in context.Agent_Commissions
group p by p.agent_code into s
select new {
holder_name = s.FirstOrDefault().holder_name,
agent_code = s.Key,
amount = s.Sum(q => q.total)
};

Here is your linq query
from a in ctx.agent_code
group a by a.holder_name, a.code into totals
select { holder_name = a.holder_name,
code = a.code,
total = totals.Sum(t=>t.total)}
Given that you have linq2sql context in ctx variable and it has your table in it.

Related

Linq query to get get count from multiple tables

I have a query wherein I need to get the count from 2 different tables. Here is a very simple form of the query (my query has more joins and conditions but this is the part I am stuck on):
select (select count(1) from Table1) as One, (select count(1) from Table2) as Two
The following linq queries works but I would like to do the above with a single linq query sent to the SQL Server. This query and many other versions I have tried, result in 2 queries sent to the server:
var query1 = from m in this.Table1 select m;
var query2 = from sr in this.Table2 select sr;
var final = new { One = query1.Count(), Two = query2.Count() };
I also tried this and this also sends 2 queries:
var final = from dummy in new List<int> { 1 }
join one in query1 on 1 equals 1 into ones
join two in query2 on 1 equals 1 into twos
select new { One = ones.Count(), Two = twos.Count()};
You need to make it a single LINQ query that can be translated:
var final = (from m in this.Table1.DefaultIfEmpty()
select new {
One = (from m in this.Table1 select m).Count(),
Two = (from sr in this.Table2 select sr).Count()
}).First();
Note that putting the sub-queries into an IQueryable variable will cause three separate queries to be sent.
Alternatively, since Count() doesn't have a query syntax equivalent, this is a little more compact in lambda syntax:
var final = this.Table1.DefaultIfEmpty().Select(t => new {
One = this.Table1.Count(),
Two = this.Table2.Count()
}).First();

How to apply Not In Linq?

I have tow tables - OrderRequisition and Order. I can show all the records from OrderRequisition table using linq query:
var list = (from r in db.OrderRequisition
select new SalesOrderViewModel
{
OrderId = r.OrderId ,
OrderNo = r.OrderNo
}).ToList();
I want to show only those records from OrderRequisition table which are not included in Order table. Any clue
Thanks
Partha
A simple approach that might be efficient enough because your database is able to optimize it:
var list = db.OrderRequisition
.Where(or => !db.Order.Any(o => o.OrderId == or.OrderId))
.ToList();
(skipped the SalesOrderViewModel initialization because not relevant for the question)

How do I convert this tSQL statement to LINQ using group by in a sub query

I have the following MSSQL query I am trying to convert to LINQ. I am using entity framework with the following syntax to get at the data.
var rv = (from i in DC.TableA select i).ToList();
This is the sql I want to write a C# LINQ query for but I cannot figure it out. Can someone help?
select BTO.*
from TableA BTO
join
(
select eqnum, max(testdate) as testdate
from TableA BTO1
where
BTO1.eqnum in ('M0435', 'Z0843') and
BTO1.testdate <= '2008-06-01'
group by eqnum
) T1
on
T1.eqnum = BTO.eqnum and
T1.testdate = BTO.testdate
order by EqNum;
I think there is opportunity to rewrite your query, but for information purposes I rewrote your sql into linq verbatim.
If you explain what you are trying to achieve we can provide alternative sql / linq
var eqnums = new[] { "M0435", "Z0843" };
var testdate = "2008-06-01";
var query = from bto in DC.TableA
join t1 in (
from bto1 in DC.TableA
where eqnums.Contains(bto1.eqnum) &&
bto1.testdate.CompareTo(testdate) <= 0
group bto1 by bto1.eqnum into g
select new
{
eqnum = g.Key,
testdate = g.Max(x => x.testdate)
}
) on new { bto.eqnum, bto.testdate } equals new { t1.eqnum, t1.testdate }
orderby bto.eqnum
select bto;

Entity Framework Query with MAX

I've been banging my head against the wall trying to translate a simple SQL Query into EF query..
Can anyone help please.. Following is the query I am trying to translate.
SELECT p.[UniqueId]
,p.[CAI]
,p.[HRGuid]
,p.[FullName]
,p.[Email]
,a.*
FROM [Participant] p
INNER JOIN
(
Select * FROM Assignment where assignmentNumber =
(Select MAX(AssignmentNumber)FROM
Assignment GROUP BY UniqueId)
) a
ON p.UniqueId = a.UniqueId
Basically I'm trying to get Participant along with their latest assignment.
You will need to create your Participant entity using Linq-Objects. You need to customize after AsEnumerable in order to create your entities
var query = (from p in context.Participant
join a in context.Assignment on p.UniqueId equals a.UniqueId into ag
select new
{
Participant = p,
Assignment = ag.OrderByDescending(x => x.AssignmentNumber).FirstOrDefault()
}).AsEnumerable()
.Select(x => new Participant(x.Participant )
{
Assignments = new Assignment[] { x.Assignment }
};

Linq issue select Sum of one column minus another from different table

This is my sql code
SELECT M.PartNo AS ModulePartNo,
(SELECT SUM(Delivered - Allocated)
FROM V_InStock Stk
WHERE Stk.PartNo = M.PartNo) AS Available
FROM V_Products M
WHERE M.PartNo='100-25897'
I am having real problems getting this to work in Linq, can't work out the sum part - any help would be really appreciated
This should work.
var query = from stk in V_InStock
group stk by stk.PartNo into stkg
where stkg.Key == '100-25897'
select new
{
ModulePartNo = stkg.Key,
Available = stkg.Sum(s => s.Delivered) - stkg.Sum(s => s.Allocated)
}
If you need to do aggregate grouping etc you will probably need to set up an object to "select" everything into. However for a straight join something like this should work.
var outputObject = (from t1 in dbContext.table1
join t2 in dbContext.table2 on t1.PartNo equals t2.PartNo
select (t1.Delivered - t2.Allocated));

Categories