I have the following SQL query which has a sub query so that only the max value is in the result set:
Select
t.ID,
r.ResultIdentifier,
p.ProductID,
r.Status,
r.Start
from Result r , Transact t, Product p
WHERE r.ResultIdentifier = (Select MAX(r2.ResultIdentifier) from Result r2
where r2.Status = 'Fail'
and r2.ID = r.ID
and r2.Start >= getdate() - 30)
and r.ID = t.ID
and p.productID = 9
and t.productID = p.productID
I'm trying to convert this to a LINQ query
var failures = from result in db.Results
join transact in db.Transacts on result.ID equals transact.ID
join product in db.Products on transact.ProductID equals product.ProductID
where result.ResultIdentifier == ??
.....
select new{ ID = transact.ID,
...etc
I'm really struggling with the max ResultIdentifier in the LINQ - tried multiple variations with .MAX() but cant seem to get it right.Any suggestions welcome.
You can use the max keyword, Sorry for using method syntax as I can see you are using query :(
Should look something like the following
where result.ResultIdentifier == (Results.Max().Where(x => x.Status.equals("Fail") && x.id == result.id && x.start => Datetime.Now().Add(-30)).Select(x => x.ResultIdentifier))
Try the following query:
var results = db.Results;
var failedResults = results
.Where(r => r.Status == "Fail" && r.Start >= DataTime.Date.AddDays(-30));
var failures =
from result in results
join transact in db.Transacts on result.ID equals transact.ID
join product in db.Products on transact.ProductID equals product.ProductID
from failed in failedResults
.Where(failed => failed.ID == result.ID)
.OrderByDescending(failed => failed.ResultIdentifier)
.Take(1)
where result.ResultIdentifier == failed.ResultIdentifier
.....
select new{ ID = transact.ID,
...etc
Related
I need to query a table and join related tables. A single query without joining another table returns the expected result. but once I join another table I get zero result.
The below query returns some results
var response = from o in context.Orders.Where(p => p.Start_Effective >= startDate && p.Start_Effective < endDate);
But once I join another table
var response = from o in context.Orders.Where(p => p.Start_Effective >= startDate && p.Start_Effective < endDate);
join v in context.Venue on o.Id equals v.Id
select new
{
Id = o.Id,
PointId = o.FromPointId,
VenueName = v.Name
};
I also try the below query and I still get zero result
var response = from o in context.Orders.Where(p => p.Start_Effective >= startDate && p.Start_Effective < endDate)
from v in context.Venue
where v.OrderId == o.Id
select new
{
Id = o.Id,
PointId = o.FromPointId,
VenueName = v.Name
};
I cant figure out why this is returning 0 result once I join table
If there is no record in Venue Table with OrderId, when inner join is used, no data returned and you should insert a record that has OrderId that exist in Order Table.
Another option is using left join.
By left join, if there is no OrderId in Venue Table, result was returned
try to use a left join, and add to list
var response = (from o in contextOrders
join v in context.Venue on o.Id equals v.Id into vj
from v in vj.DefaultIfEmpty()
where ( o.Start_Effective >= startDate && o.Start_Effective < endDate)
select new
{
Id = o.Id,
PointId = o.FromPointId,
VenueName = v.Name
}).ToList();
I have the following method for filtering shops by the criteria specified in parameters:
public int[] GetShopIds(IEnumerable<Guid> OrderCreaatorIds, IEnumerable<Guid> OrderItemCategoryIds, int StatusId)
{
var query = from s in _db.Shops
join o in _db.Orders on s.Id equals o.ShopId
join oi in _db.OrderItems on o.Id equals oi.OrderId
where
OrderCreaatorIds.Contains(o.CreatorId)
&& OrderItemCategoryIds.Contains(oi.CategoryId)
&& (int)o.StatusId == StatusId
select s.Id;
return query.ToArray();
}
The thing is: OrderCreaatorIds, OrderItemCategoryIds can be null and StatusId can be 0. In that case I do not want to have those where clauses, e.g. if OrderCreaatorIds is null then the query should work as follows:
public int[] GetShopIds(IEnumerable<Guid> OrderCreaatorIds, IEnumerable<Guid> OrderItemCategoryIds, int StatusId)
{
var query = from s in _db.Shops
join o in _db.Orders on s.Id equals o.ShopId
join oi in _db.OrderItems on o.Id equals oi.OrderId
where
OrderItemCategoryIds.Contains(oi.CategoryId)
&& (int)o.StatusId == StatusId
select s.Id;
return query.ToArray();
}
etc.
Unfortunately where OrderCreaatorIds != null && OrderCreaatorIds.Contains(o.CreatorId) is not working.
public int[] GetShopIds(IEnumerable<Guid> OrderCreaatorIds, IEnumerable<Guid> OrderItemCategoryIds, int StatusId)
{
var query = from s in _db.Shops
join o in _db.Orders on s.Id equals o.ShopId
join oi in _db.OrderItems on o.Id equals oi.OrderId
select new { s = s, o = o, oi = oi };
if (null != OrderCreaatorIds)
query = query.Where(x_ => OrderCreaatorIds.Contains(x_.o.CreatorId));
if (null != OrderItemCategoryIds)
query = query.Where(x_ => OrderItemCategoryIds.Contains(x_.oi.CategoryId));
if (0 < StatusId)
query = query.Where(x_ => (int)x_.o.StatusId == StatusId);
return query.select(x_ => x_.s.Id).ToArray();
}
Maybe you will have to add some casting to IQueryable<> to make it compilable. I did not check it in compiler.
Try something like the following:
var query = from s in _db.Shops
join o in _db.Orders on s.Id equals o.ShopId
join oi in _db.OrderItems on o.Id equals oi.OrderId
where
(OrderCreaatorIds==null || OrderCreaatorIds.Contains(o.CreatorId))
&&
(OrderItemCategoryIds==null || OrderItemCategoryIds.Contains(oi.CategoryId))
&&
(StatusId==0 || (int)o.StatusId == StatusId)
select s.Id;
As you can see for each part of the where clause I have changed it from your simple predicate to an or check of two predicates. So now you have three things that are formed like A || B. Due to the way or logic works if A is true then B will be ignored. So in this case if OrderItemCategoryIds is null then it won't do the OrderItemCategoryIds.Contains check.
You can prepare the dynamic parts of the query in variables outside the query, and then use the variables inside like this:
public int[] GetShopIds(IEnumerable<Guid> OrderCreaatorIds, IEnumerable<Guid> OrderItemCategoryIds, int StatusId)
{
var orders = _db.Orders.AsQueryable();
if (StatusId != 0)
orders = orders.Where(o => o.StatusId == StatusId);
if (OrderCreaatorIds != null)
orders = orders.Where(o => OrderCreaatorIds.Contains(o.CreatorId));
var orderItems = _db.OrderItems;
if (OrderItemCategoryIds != null)
orderItems = orderItems.Where(oi => OrderItemCategoryIds.Contains(oi.CategoryId));
var query = from s in _db.Shops
join o in orders on s.Id equals o.ShopId
join oi in orderItems on o.Id equals oi.OrderId
select s.Id;
return query.ToArray();
}
I need extra where clause for my Linq query. For example if customer choose a date filter so i need to date filter to my query etc... When i try to myQuery.Where predicate there is visible just group by's field.
How can i append new where condition to my query.
//for example i need dynamically append o.OrderDate==Datetime.Now or another where clause
var myQuery =(from o in _db.Orders
join l in _db.OrderLines.Where(x => x.ParaBirimi == model.ParaBirimi) on o.orderId equals
l.OrderId
where o.OrderDate.Value.Year == year1
group o by new {o.OrderDate.Value.Month}
into g
select
new
{
Month = g.Key.Month,
Total = g.Select(t => t.OrderLines.Sum(s => s.OrderTotal)).FirstOrDefault()
});
You are too late at the end of the query to add new Where. You have already grouped the data, and projected it, removing nearly all the fields.
Try:
var baseQuery = from o in _db.Orders
join l in _db.OrderLines.Where(x => x.ParaBirimi == model.ParaBirimi) on o.orderId equals l.OrderId
where o.OrderDate.Value.Year == year1
select new { Order = o, OrderLine = l };
if (something)
{
baseQuery = baseQuery.Where(x => x.Order.Foo == "Bar");
}
var myQuery = (from o in baseQuery
group o by new { o.Order.OrderDate.Value.Month }
into g
select
new
{
Month = g.Key.Month,
Total = g.Sum(t => t.OrderLine.OrderTotal)
});
Clearly you can have multiple if. Each .Where() is in && (AND) with the other conditions.
Note how the result of the join is projected in an anonymous class that has two properties: Order and OrderLine
I am writing to write this SQL query in linq, but didnt work..
select [ProcessTime], Count([ID]) as 'amount of processes'
from [DB].[dbo].[TableX]
where [ID] in ('ServerX', 'ServerY') and [Type] ='Complete'
group by [ProcessTime]
order by [ProcessTime]
I would like to achieve this linq & what I have tried , I split the query into two, one for process time group by clause and another to count the ID's
var query1 = (from a in this.db.Processes
where (a.ID =='ServerX' || a.ID =='ServerY') && a.Type =='Complete'
group a by a.ProcessTime into b
//here I dont know where to place orderby
select b);
var query2 = (from a in this.db.Processes
where (a.ID =='ServerX' || a.ID =='ServerY') && a.Type =='Complete'
orderby a.ProcessTime
select a).Count();
is this the right way to split the query into two and then later combine them ?
Try this:
var serverNames = new string[]{"ServerX", "ServerY"};
var result = db.Processes
.Where(p => serverNames.Contains(p.ID) && p.Type == "Complete")
.GroupBy(p => p.ProcessTime)
.Select(g => new
{
ProcessTime = g.Key,
AmountOfProcesses = g.Count()
})
.OrderBy(x => x.ProcessTime);
You can do all this in one query:
var query1 = (from a in this.db.Processes
where (a.ID == "ServerX" || a.ID == "ServerY") && a.Type == "Complete"
group a by a.ProcessTime into b
orderby b.Key
select new {ProcessTime = b.Key, Count = b.Count()});
What is the best way to write this query in linq?
SELECT *
FROM product_master
where product_id in (select product_id from product where buyer_user_id=12)
var _result = from a in product_master
where (product.Where(s => s.buyer_user_id == 12))
.Contains(a.product_ID)
select a;
or
var _result = (from a in product_master
join b in product
on a.product_id equals b.product_id
where b.buyer_user_id == 12
select a).Distinct();
JW's answer is correct. Alternatively, given that the subquery is not correlated, you could express it separately:
var pids = product.Where(p => p.buyer_user_id == 12);
var r = product_master.Where(pm => pids.Contains(pm.product_id));