LINQ Query with join, group by and Sum() - mysql

I've working on this for a while so I thought I'd post here to see if anyone has any idea how a query like the following can be converted to LINQ.
Here is the MySQL Query:
SELECT SUM(line_ord.itemqty) AS LineOrderQTY, SUM(assemblyNumber.qty) AS
AssemblyQTY FROM line_ord
LEFT JOIN
(
SELECT sum(assemblyno.qty) AS qty, assemblyno.row_id FROM assemblyno
INNER JOIN line_ord ON assemblyno.row_id = line_ord.row_id
WHERE line_ord.bdnum = 'S61460'
) AS assemblyNumber ON line_ord.row_id = assemblyNumber.row_id
WHERE line_ord.bdnum = 'S61460'
This what I have so far for the LINQ query, but it doesn't return the proper results.
var items = (from c in Context.OrderLineItemData
join e in Context.AssemblyLabelData on c.ID equals e.RowID
where c.BreakdownNumber == breakdownNumber
group c by c.BreakdownNumber into g
select new
{
AssemblyQuantity= g.Sum(x => x.Quantity),
LineOrdQuantity = g.Sum(**WHAT GOES HERE?**)
}).FirstOrDefault()
I did manage to get it to work like this, but it seems kind of messy to me.
var items = (from c in Context.OrderLineItemData
join e in Context.AssemblyLabelData on c.ID equals e.RowID
where c.BreakdownNumber == breakdownNumber
group c by c into g
select new
{
AssemblyQuantity= g.Sum(x => x.Quantity),
LineOrdQuantity = (from e in Context.OrderLineItemData where e.BreakdownNumber == breakdownNumber select e.Quantity).Sum()
}).FirstOrDefault();
Is there a better way to do this?

Got my answer. Seems like a query object has to be created and then I can use it to preform my calculations.
var items = (from od in Context.OrderLineItemData
join ad in Context.AssemblyLabelData on od.ID equals ad.RowID into odGroup
from g in odGroup.DefaultIfEmpty()
where od.BreakdownNumber == breakdownNumber
group g by new
{
breakdown = od.BreakdownNumber,
LineOrd = od,
AssemblyQty = g == null ? 0 : g.Quantity
}
into groupped
select new
{
Breakdown = groupped.Key.breakdown,
AssemblyQty = groupped.Sum(x => x.Quantity),
lineOrdQty = groupped.Key.LineOrd.Quantity
}
);
int remainingQuantity = items.Sum(x => x.lineOrdQty) - items.Sum(x => x.AssemblyQty);

Related

The Linq SqlExpression query for select list is not being sorted

I have an Linq sql query as given below. But the depot number is not coming as sorted order. I want to show drop down list as depotno order . But it is showed as '1','18','19','2'. I want to show it as '1','2' and so on
IEnumerable<SelectListItem> depotUserList = (from e in ctx.goUserDepartment
join c in ctx.goDepot on e.DepotNo equals c.DepotNo
join user in ctx.goUser
on e.UserID equals user.UserID
where e.UserID == UserID &&
e.IsDeleted == false
orderby c.DepotNo
select new SelectListItem
{
Value = c.DepotNo.ToString(),
Text = c.DepotName,
Selected = user.DepotNo == e.DepotNo
}).Distinct().ToList<SelectListItem>();
It seems that your DepotNo type is string type, I suggest you could try to order the result after ToList method.
Like this:
IEnumerable<SelectListItem> depotUserList = (from e in ctx.goUserDepartment
join c in ctx.goDepot on e.DepotNo equals c.DepotNo
join user in ctx.goUser
on e.UserID equals user.UserID
where e.UserID == UserID &&
e.IsDeleted == false
select new SelectListItem
{
Value = c.DepotNo.ToString(),
Text = c.DepotName,
Selected = user.DepotNo == e.DepotNo
}).Distinct().ToList<SelectListItem>().OrderBy(x=> int.Parse(x.Value));

GroupBy LINQ to SQL not working, perhaps

I'm struggling to get groupby working in LINQ to SQL, im pretty new to it...I trying to groupby g.id but it just wont work...any help would be greatly appreciated...Cheers
IQueryable<GuestList> query = from t in _ttx.Trips
join l in _ttx.Legs on t.Id equals l.TripId
join gl in _ttx.GuestLegs on l.Id equals gl.LegId
join g in _ttx.Guests on gl.GuestId equals g.Id
where t.Id == id
select new GuestList()
{
Id = g.Id,
Name = g.Name,
NoOfLegs = g.GuestLegs.Count()
};
My result is
1 paul 3
2 Jim 1
1 paul 3
1 paul 3
Please try is as below.
var query2 = (from ps in query
group ps by new { ps.Id } into prod
select new GuestList
{
Id = prod.Key.Id,
Name = prod.Name,
NoOfLegs = prod.Sum(c => c.NoOfLegs),
}).OrderBy(x => x.Id).ToList();

Left join with multiple tables and conditions

I want to sort after a value in another table the current table is referenced to. My query looks like this:
SELECT o._id,
o.titel,
o.beschreibung
FROM `objekt` AS o,
`objekt_einzel` AS oe,
`objekt_einzel_immobilie` AS oei,
`objekt_art` AS oa,
`verortung` AS v
#here
,`person` AS p,
`person_bauträger` AS pb
#end
WHERE o._id = oe.objekt_id
AND oe._id = oei.objekt_einzel_id
AND oa._id = o.objekt_art_id
AND o.ort_id = v._id
#here
AND oe.bauträger_id = pb._id
AND pb.person_id = p._id
#end
AND ( oei.justimmo_objekt_id = "0"
OR oei.justimmo_objekt_id IS NULL
OR oei.justimmo_objekt_id = "" )
#here
ORDER BY p.firmenbezeichnung ASC
The query is working fine but it shows me only values if oe.bauträger_id is set. I also want the null values. So I need a left join. I tried different things but I only get messages like unknown column or I get too much results.
I tried to simplify it to this:
SELECT o._id,
o.titel,
o.beschreibung
FROM `objekt` AS o,
`objekt_einzel` AS oe,
(SELECT oe.bauträger_id
FROM objekt o, objekt_einzel oe, objekt_einzel_immobilie oei
WHERE o._id = oe.objekt_id AND oe._id = oei.objekt_einzel_id) AS menge1
LEFT JOIN
(SELECT pb._id AS bauträger_id
FROM person p, person_bauträger pb
WHERE p._id = pb.person_id) AS menge2
ON menge1.bauträger_id = menge2.bauträger_id
WHERE o._id = oe.objekt_id AND oe.bauträger_id = menge1.bauträger_id
but here I get a too big result set. I don't know how to explain this better. The data sets are too big to create an example. I hope you understand what I mean.
SELECT o._id,
o.titel,
o.beschreibung
FROM `objekt` AS o
JOIN `objekt_einzel` AS oe ON o._id = oe.objekt_id
JOIN `objekt_einzel_immobilie` AS oei ON oe._id = oei.objekt_einzel_id
JOIN `objekt_art` AS oa ON o.objekt_art_id = oa._id
JOIN `verortung` AS v ON o.ort_id = v._id
LEFT JOIN `person_bauträger` AS pb ON oe.bauträger_id = pb._id
LEFT JOIN `person` AS p ON pb.person_id = p._id
WHERE oei.justimmo_objekt_id = "0"
OR oei.justimmo_objekt_id IS NULL
OR oei.justimmo_objekt_id = ""
ORDER BY p.firmenbezeichnung ASC
This second try should work as it is just the original code rewritten using JOIN syntax and with LEFT JOINs.

Join two tables using LINQ Query and order based two parameters

I have two tables Customers and Orders. I want a LINQ query to fetch list of all the orders placed by all the customers organized first by month and then by year. If there is no order corresponding to the customer, "No Orders” should be displayed.
The columns of Customers table are
customer_id
name
city
The columns of Orders table are
order_id
order_date
order_total
customer_id
I tried writing it the following way but its not giving complete output.
var res = from cust in db.Customers
join ord in db.Orders
on cust.customer_id equals ord.customer_id into g
from d in g.DefaultIfEmpty()
select new {
name=cust.name,
oId=d.order_id==null?-1:d.order_id
};
How do I rectify it?
I finally got the right answer which exactly the result as expected. I have put it below. I have used two LINQ queries to arrive at the result though. The first one gives the result, but the final result needs to be displayed with names of customer and their order totals, hence it is partial result. The second LINQ query further refines the 'partialResult' and gives the result as expected.
var partialResult = (from c in db.Customers
join o in db.Orders
on c.customer_id equals o.customer_id
select new
{c.name,
o.order_total,
o.order_date }).OrderBy(m => m.order_date.Month).ThenBy(y => y.order_date.Year);
var finalResult = from c in db.Customers
orderby c.name
select new
{
name = c.name,
list = (from r in partialResult where c.name == r.name select r.order_total).ToList()
};
foreach (var item in finalResult)
{
Console.WriteLine(item.name);
if (item.list.Count == 0)
{
Console.WriteLine("No orders");
}
else
{
foreach (var i in item.list)
{
Console.WriteLine(i);
}
}
}
Something like this. You can do it using LINQ Predicates
var res = Customers.Join(Orders, x => x.customer_id, y => y.customer_id, (x, y) => x).ToList();
This is what you can do:
var res = from cust in db.Customers
join ord in db.Orders
on cust.customer_id equals ord.customer_id into g
from d in g.DefaultIfEmpty()
orderby d.OrderDate.Year, d.OrderDate.Month
select new {
name=cust.name,
oId = d.order_id.ToString() ?? "No Orders"
};

Equivalent LINQ to SQL query

Can anyone help me with the equivalent LINQ query for the SQL below?
I am new to LINQ
Select * From Students_History SH
Where SH.Active = 1 and SH.ModifiedAt in (
select MAX(SH1.ModifiedAt)from Students_History SH1
group by SH1.StudentId)
This is what I have tried
var q =
from h in Students_History
where h.Active=1
group h by h.StudentId into g
select new
{
StudentID = g.Key,
LatestModified = g.Max (x => x.ModifiedAt)
}
This linq query does not give me the right result and somehow the active=1 is ignored
I have about dozen fields in my Students_History table and I want all those fields not just studentId and ModifiedAt.
Try this:
var q =
from hg in Students_History
group hg by hg.StudentId into g
join h in Students_History on g.Key equals h.StudentId
where h.Active == 1 && h.ModifiedAt == g.Max(x => x.ModifiedAt)
select new
{
StudentID = h.StudentId,
LatestModified = h.ModifiedAt
}
You need to compare using the == operator.