Group By and Sum In LINQ query with Join - c#

I have a query in C# and i need to group by this query for c.Same_invoice and sum the column price in the row grouped.
I know how to do group by and sum but i don't know the solution for my case, with a join and a large amount of data.
The actual code is:
var query = from c in snd.external_invoices.OrderByDescending(x => x.date)
join o in snd.invoices on c.idexternal_invoices equals o.id_external_invoice
select new{
c.idexternal_invoices,
c.businessname,
o.number,
c.message,
c.price,
c.date,
c.iduser
};
Thank to all

You can use something like:
var query = from c in snd.external_invoices.OrderByDescending(x => x.date)
join o in snd.invoices on c.idexternal_invoices equals o.id_external_invoice into grouped
select new{
Invoice =grouped.key, Price = grouped.Sum(x => x.Price)};

Related

Trouble translating SQL query to LINQ with join and having count

I have this SQL query that I need to translate to LINQ.
SELECT p.productId, p.name, COUNT(np.ID) AS 'salesLast70', p.quantity
FROM Products p
LEFT JOIN NOrderProducts np
ON np.product_id = p.productId
WHERE np.date_picked > DATEADD(DAY, -70, getdate())
GROUP BY p.productId, p.name, p.quantity
HAVING COUNT(np.ID) < p.quantity
Right now I have the following LINQ query.
var date70 = DateTime.Now.AddDays(-70).Date;
var almostOutOfStockProducts = from p in db.Products
join np in db.NOrderProducts on p.productId equals np.product_id
where np.date_picked > date70
group np by np.ID into npGrp
where npGrp.Count() < p.quantity
select p;
But p cannot be resolved at the end of the LINQ query at > p.quantity and select p.
I'm sure I am missing something in my LINQ query but I cannot seem to find exactly how to fix it.
EDIT:
I ended up using db.Database.SqlQuery(); with the raw query.
To achieve what you want you have to lift the quantity, name from the product up into the group by. You are doing this in your sql version with the clause GROUP BY p.productId, p.name, p.quantity but you are not doing this in your linq version.
An example would be to do:
var almostOutOfStockProducts = db.Products.Join(db.NOrderProducts, p => p.productId, np => np.product_id, (p, np) => new { p, np })
.Where(x => x.np.date_picked > date70)
.GroupBy(x => new { Quantity = x.p.quantity, Name = x.p.name, ProductId = x.p.productId})
.Where(x => x.Count() < x.Key.Quantity)
.Select(x => new {ProductId = x.Key.ProductId, Quantity = x.Key.Quantity, Name = x.Key.Name});
In the GroupBy I am bringing through the product id, quantity and name from the product into an anonymous type. This then becomes the key so I can use it in the Where clause and also in the Select at the end.

Concentrating a join into a single column in linq query

I have the following query:
var query = (from wo in _dbContext.WorkOrder
join opr in _dbContext.Operation
on wo.operationID equals opr.operationID
where wo.orderid == selectedorderid
select new {wo.orderid, wo.workOrderID, wo.itemID, wo.operationID, opr.operationName, wo.operationCode}).ToList();
I also have another table,which joins with workorder table,and returns multiple values.
What I want to do is,I want to join the table and get a single column of it as a concentrated column in my query such as (id1,id2,id3) etc. How can I achieve this?
What about:
var query = (from wo in _dbContext.WorkOrder
join opr in _dbContext.Operation
on wo.operationID equals opr.operationID
where wo.orderid == selectedorderid
select new {wo.orderid, wo.workOrderID, wo.itemID, wo.operationID, opr.operationName, wo.operationCode}).ToList();
var orders = queryGroupBy(i => i.workOrderID)
.Select(i => new {WorkOrderId = i.workOrderID, ConcatinatedIds = String.Join(", ", i.Select(j => j.operationID))})
.ToList();

Changing a SQL query to a linq query - syntax

I'm having problem coding my linq query.
This is my SQL query:
select
price, (cast(sum(Quantity) as decimal(7,2)))
from
OrderDetails
where
ItemID = 1000
group by
price
order by
price
This is my linq query:
var result = from od in db.OrderDetails
where od.ItemID == 1000
orderby od.Price
group by price
select od.price, (cast(sum(od.Quantity) as decimal(7, 2)));
This linq query seems to be incorrect. What is the right syntax?
This should work:
(You need to move the order part to be after the grouping)
var q = (from o in context.OrderDetails
where o.ItemID == 1000
group o by o.price into grp
select new
{
Price = grp.Key,
Quantity = grp.Sum(x => x.Quantity)
}).OrderBy(a => a.Price);

Replacing SQL join and group query with linq query in Entity Framework

I have an existing SQL query:
select
mn.accountid, sum(u.peak), sum(u.text), sum(u.datagig),
sum(p.minutesallowed), sum(p.messagesallowed), sum(p.dataallowed)
from
usage u
inner join
mtn mn on u.mtnid = mn.Id
inner join
[plan] p on p.id = mn.planid
group by
mn.accountid
Using Entity Framework, I'm working on converting this to linq, and I've gotten this far:
var tots = from u in currentUsage
join mn in mtns on u.mtnId equals mn.Id
join p in plans on mn.PlanId equals p.Id
group u by u.AccountId into g
select new MainUsageResults
{
TotalPeakMinutes = g.Sum(x => x.Peak),
TotalData = g.Sum(x => x.DataGig),
TotalMessaging = g.Sum(x => x.Text),
TotalAllowedMinutes = g.Sum(x => ???) ,
TotalAllowedMessages = g.Sum(x => ???) ,
TotalAllowedData = g.Sum(x => ???)
};
I can't figure out how to sum up the data that is on the joined tables. In SQL one would have the whole set of columns available in a join, but it doesn't seem to be the case here. How do I get the sum of the columns on the joined tables in this example?
Thanks to #3-14159265358979323846264, a real nice example can be found here

Join all the sublists together and grab the first one

I want to be able to pull the last invoice containing a product in a category
Category->Product->Invoice
(from p as Product in cat
where p.InvoiceList.Where(function(o) o.InvoiceDate >= MAX_ONE)
select p.InvoiceList.Where(function(o) o.InvoiceDate >= MAX_ONE)
).FirstOrDefault()
I just can't seem to wrap my head about how to get this done.
EDIT: a sample SQL statement that would accomplish my goal. If only I could translate it...
SELECT TOP 1 i.InvoiceID, i.InvoiceDate, i.TotalAmount
FROM Category as c INNER JOIN
Product as p ON p.categoryID = c.categoryID INNER JOIN
InvoiceProducts as ip ON ip.productID = p.productID INNER JOIN
Invoice as i ON ip.InvoiceID = i.InvoiceID
WHERE c.categoryID = 3
ORDER BY InvoiceDate DESC
cat.SelectMany(p => p.InvoiceList).OrderBy(o => o.InvoiceDate).LastOrDefault();
var lastInvoice = (from i in context.Invoices
.where i.Product.CategoryId == categoryId
.select i)
.OrderByDescending(i=>i.IbvoiceDate)
.FirstOrDefault();

Categories