I am posting one more doubt of mine:
Is there a way by which we can use the result of one query and then join the same further just like we do in SQL:
SELECT Applications.* , ApplicationFees.ApplicationNo, ApplicationFees.AccountFundDate1,ApplicationFees.AccountFundDate2 ,ApplicationFees.AccountFundDate3 , ApplicationFees.AccountCloseDate1, ApplicationFees.AccountCloseDate2,ApplicationFees.AccountCloseDate3,
isnull(SUBQRY11.AMNT ,0) as SCMSFEE1R,
isnull(SUBQRY12.AMNT,0) as SCMSFEE2R,
Left Join
(
SELECT ApplicationNo,COUNT(ApplicationNo) AS CNT, SUM(Amount) as AMNT
FROM Payments where (FEETYPE=1 AND FeePosition=1) and (FeeDate>='2011-01-01')
and (FeeDate<='2012-01-01')
GROUP BY ApplicationNo
)SUBQRY11
ON ApplicationFees.ApplicationNo= SUBQRY11.ApplicationNo
Left Join
(
SELECT ApplicationNo,COUNT(ApplicationNo) AS CNT2, SUM(Amount) as AMNT
FROM Payments where (FEETYPE=1 AND FeePosition=2) and (FeeDate>='2011-01-01')
and (FeeDate<='2012-01-01')
GROUP BY ApplicationNo )SUBQRY12 ON ApplicationFees.ApplicationNo=SUBQRY12.ApplicationNo
I want to avoid the same in foreach of the query as that will be quite time consuming.
Yes, you can join sub queries. Like this:
var query = from f in db.ApplicationFees
join sub in (from p in db.Payments
where p.Type == 1 && p.Position == 1 &&
p.Date >= fromDate && p.Date <= toDate
group p by p.ApplicationNo into g
select new {
ApplicationNo = g.Key,
CNT = g.Count(),
AMNT = g.Sum(x => x.Amount)
})
on f.ApplicationNo equals sub.ApplicationNo into feePayments
select new { Fee = f, Payments = feePayments };
But writing it in single query is not very maintainable. Consider to compose your query from sub-queries defined separately:
var payments = from p in db.Payments
where p.Type == 1 && p.Position == 1 &&
p.Date >= fromDate && p.Date <= toDate
group p by p.ApplicationNo into g
select new {
ApplicationNo = g.Key,
CNT = g.Count(),
AMNT = g.Sum(x => x.Amount)
};
var query = from f in db.ApplicationFees
join p in payments
on f.ApplicationNo equals p.ApplicationNo into feePayments
select new { Fee = f, Payments = feePayments };
Related
Hello I need to crate linq query from this SQL:
SQL:
select
p.id,
p.Name,
sum(h.Hour)
from
dbo.Hour h
INNER JOIN dbo.ProjectView p ON h.ProjectId = p.Id
WHERE
h.PeopleId = 7999
group by
p.Name, p.Id
LINQ: I tried this but it is not the same:
var query = from hours in _hourRepository.GetAll()
join proj in _projectRepository.GetAll() on hours.ProjectId equals proj.Id
where hours.PeopleId == personId
group hours by new { proj.Id, proj.Name, proj.Flag, hours.Hours } into g
select new PopleProjectsSumDto
{
Id = g.Key.Id,
Name = g.Key.Name,
Flag = g.Key.Flag,
Hours = g.Sum(h => h.Hours)
};
OK i find solution by removing hours from group:
LINQ:
var query = from hours in _hourRepository.GetAll()
join proj in _projectRepository.GetAll() on hours.ProjectId equals proj.Id
where hours.PeopleId == personId
group hours by new { proj.Id, proj.Name, proj.Flag } into g
select new PopleProjectsSumDto
{
Id = g.Key.Id,
Name = g.Key.Name,
Flag = g.Key.Flag,
Hours = g.Sum(h => h.Hours)
};
I'm doing a query (see below), but I do not know how to retrieve all data from a select.
var model = new dbContext();
var query = from mp in model.matiere_premiere join req in (from stk in model.stock_mp
join ms in model.matiere_premiere
on stk.matiere_premiere_code equals
ms.code
where stk.date <= DateTime.Today
orderby stk.date descending
select new new { stk.qte, stk.matiere_premiere_code })
on mp.code equals req.matiere_premiere_code
group mp by new { mp.code } into grp
orderby grp.Key
select new
{
grp.Key,
grp.First().designation,
grp.Last().frns
};
The equivalent sql query is:
SELECT matiere_premiere.code,matiere_premiere.designation,
"matiere_premiere.unite, matiere_premiere.frns ,IF(ISNULL(REQ.qte), '0.00', REQ.qte) AS qte
FROM matiere_premiere LEFT JOIN (SELECT qte,matiere_premiere_code FROM stock_mp
JOIN matiere_premiere ON matiere_premiere.code = matiere_premiere_code
WHERE DATE <= CURRENT_DATE() ORDER BY DATE DESC)
AS REQ ON REQ.matiere_premiere_code = matiere_premiere.code
GROUP BY matiere_premiere.code ORDER BY matiere_premiere.code
it's simple, the group is also an enumerator, so you should return
select grp;
then, for each group, you can do a foreach of the values
foreach(var group in query)
{
Console.WriteLine("Key: " + group.Key);
foreach(var v in group)
{
Console.WriteLine("Value: " + v.Property);
}
}
My linq query
from report in CustomerDayReports
join payments in CustomerPayments on new { report.CustomerId, report.CurrencyId } equals new { payments.CustomerId, payments.CurrencyId } into j
from j2 in j.DefaultIfEmpty()
group report by new { report.CustomerId, report.CurrencyId } into g1
select new
{
Customer = g1.Key.CustomerId,
Currency = g1.Key.CurrencyId,
Debt = g1.Sum(x => x.Value * x.Amount)
}
Result SQL
SELECT
SUM([t0].[Value] * [t0].[Amount]) AS [Debt],
[t0].[CustomerId] AS [Customer],
[t0].[CurrencyId] AS [Currency]
FROM [CustomerDayReport] AS [t0]
LEFT OUTER JOIN [CustomerPayment] AS [t1]
ON ([t0].[CustomerId] = [t1].[CustomerId]) AND ([t0]. [CurrencyId] = [t1].[CurrencyId])
GROUP BY [t0].[CustomerId], [t0].[CurrencyId]
How modify linq for get next SQL?
*SUM([t0].[Value] * [t0].[Amount])*
to
*T0.SUM([t0].[Value] * [t0].[Amount])* - ISNULL(SUM([T1].Amount)
SELECT
SUM([t0].[Value] * [t0].[Amount]) - ISNULL(SUM([t1].Amount), 0) AS [Debt],
[t0].[CustomerId] AS [Customer],
[t0].[CurrencyId] AS [Currency]
FROM [CustomerDayReport] AS [t0]
LEFT OUTER JOIN [CustomerPayment] AS [t1]
ON ([t0].[CustomerId] = [t1].[CustomerId]) AND ([t0]. [CurrencyId] = [t1].[CurrencyId])
GROUP BY [t0].[CustomerId], [t0].[CurrencyId]
Correct grouping is
group new {report, payments} by new { report.CustomerId, report.CurrencyId } into g
All query is
from report in CustomerDayReports
join payments in CustomerPayments on new { report.CustomerId, report.CurrencyId } equals new { payments.CustomerId, payments.CurrencyId } into j
from payments in j.DefaultIfEmpty()
group new {report, payments} by new { report.CustomerId, report.CurrencyId } into g
select new
{
Customer = g.Key.CustomerId,
Currency = g.Key.CurrencyId,
Debt = g.Sum(x => x.report.Value * x.report.Amount) - ((decimal?) g.Sum(x => x.payments.Amount) ?? (decimal?)0)
}
I have a query returning some values for a specific CompanyId and a Specific Month/Year.
I want to make a report for the whole year. (So I need to sum up the values from different months, but of the same year and CompanyId)
Here is my query now:
from er in EconomicReports
join com in Companies on er.CompanyId equals com.Id
join cou in Countries on com.CountryId equals cou.Id
where er.Year == 2014
select new
{
Country = cou.Name,
CompanyId = com.Id,
CorporationId = com.CorporationId,
Year = er.Year,
RegisteredCases = er.NewCasesTotalCount,
RegisteredCasesAmount = er.NewCasesTotalAmount,
ResolvedCases = er.ClosedCasesTotalCount,
ResolvedCasesAmount = er.ClosedCasesCapitalAmount + er.ClosedCasesInterestAmount,
ActiveCases = (er.NewCasesTotalCount ?? 0) - (er.ClosedCasesTotalCount ?? 0),
ActiveCasesAmount = (er.NewCasesTotalAmount ?? 0) - (er.ClosedCasesCapitalAmount ?? 0) - (er.ClosedCasesInterestAmount ?? 0)
}
Basically, rows 1 and 5 need to be one row, because they are from the same year, same company Id (I have put also Month in the results for you to see that is a different month, but same year)
you need a GroupBy:
var query = (from er in EconomicReports
join com in Companies on er.CompanyId equals com.Id
join cou in Countries on com.CountryId equals cou.Id
where er.Year == 2014
select new
{
Country = cou.Name,
CompanyId = com.Id,
CorporationId = com.CorporationId,
Year = er.Year,
RegisteredCases = er.NewCasesTotalCount,
RegisteredCasesAmount = er.NewCasesTotalAmount,
ResolvedCases = er.ClosedCasesTotalCount,
ResolvedCasesAmount = er.ClosedCasesCapitalAmount + er.ClosedCasesInterestAmount,
ActiveCases = (er.NewCasesTotalCount ?? 0) - (er.ClosedCasesTotalCount ?? 0),
ActiveCasesAmount = (er.NewCasesTotalAmount ?? 0) - (er.ClosedCasesCapitalAmount ?? 0) - (er.ClosedCasesInterestAmount ?? 0)
});
var result = query
.GroupBy(u => new {u.Country, u.CompanyId, u.CorporationId, u.Year})
.Select(u => new
{
Country = u.Key.Country,
CompanyId = u.Key.CompanyId,
CorporationId = u.Key.CorporationId,
Year = u.Key.Year,
RegisteredCases = u.Select(t => t.RegisteredCases).DefaultIfEmpty().Sum(),
RegisteredCasesAmount = u.Select(t => t.RegisteredCasesAmount).DefaultIfEmpty().Sum(),
ResolvedCases = u.Select(t => t.ResolvedCases).DefaultIfEmpty().Sum(),
ResolvedCasesAmount = u.Select(t => t.ResolvedCasesAmount).DefaultIfEmpty().Sum(),
ActiveCases = u.Select(t => t.ActiveCases).DefaultIfEmpty().Sum(),
ActiveCasesAmount = u.Select(t => t.ActiveCasesAmount).DefaultIfEmpty().Sum()
})
.ToList();
i think Country and CorporationId must be same for grouped records based on CompanyId and Year, so i was included them in group by, to use in Select
I have an SQL statement and I want to convert it to LINQ. The problem now is that I don't know how to group by it in LINQ.
Here is the code.
In SQL
select plp.ProspectsListID, p.Prospect_PII_Key
from ProspectListProspect plp
join Prospects p
on p.ProspectsID = plp.ProspectsID
group by plp.ProspectsListID,p.Prospect_PII_Key
In LINQ
var list1 = from plp in GetDataContext.SQLDataContext.GetTable<DataAccess.ProspectListProspect>()
join p in GetDataContext.SQLDataContext.GetTable<DataAccess.Prospect>()
on plp.ProspectsID equals p.ProspectsID
select new
{
ProspectID = plp.ProspectsListID,
Prospect_PII_Key = p.Prospect_PII_Key
};
thanks
Jason
tyr this
var list1 = from item in
(
from plp in GetDataContext.SQLDataContext.GetTable<DataAccess.ProspectListProspect>()
join p in GetDataContext.SQLDataContext.GetTable<DataAccess.Prospect>()
on plp.ProspectsID equals p.ProspectsID
select new
{
ProspectID = plp.ProspectsListID,
Prospect_PII_Key = p.Prospect_PII_Key
}
)
group item by new {item.ProspectID ,item.Prospect_PII_Key } into grp
select new
{
ProspectID = grp.ProspectsListID,
Prospect_PII_Key = grp.Prospect_PII_Key
}
;
Check this
var list1 = from plp in GetDataContext.SQLDataContext.GetTable<DataAccess.ProspectListProspect>()
join p in GetDataContext.SQLDataContext.GetTable<DataAccess.Prospect>()
on plp.ProspectsID equals p.ProspectsID
Group By Key = New With {plp.ProspectsListID,p.Prospect_PII_Key} Into Group
Select Group;
var list1 = from plp in GetDataContext.SQLDataContext.GetTable<DataAccess.ProspectListProspect>()
join p in GetDataContext.SQLDataContext.GetTable<DataAccess.Prospect>()
on plp.ProspectsID equals p.ProspectsID
group p by new {plp.ProspectsListID,p.Prospect_PII_Key} into g
select new
{
ProspectID = g.Key.ProspectsListID,
Prospect_PII_Key = g.Key.Prospect_PII_Key
};