I'm trying to translate this SQL sentence to LINQ but I'm very new in LINQ
select professor.nom, professor.llinatge,
SUM(case when falta.aprovada = 1 then 1 else 0 end) as FJ,
SUM(case when falta.aprovada = 0 then 1 else 0 end) as FNJ
from falta inner join professor on falta.id_profe = professor.id_profe
group by professor.llinatge, professor.nom
I can't get work this in LINQ with JOINs. My best aproach to this in LINQ was:
var query = from f in db.falta
join p in db.professor
on f.id_profe equals p.id_profe
group f by new {p.nom, p.llinatge, f.aprovada} into g
select new
{
nombre = g.Key.nom + " "+ g.Key.llinatge,
fj = g.Select(s=> s.aprovada == true).Count(),
fnj = g.Select(s=> s.aprovada == false).Count()
};
Thank you!
You may try SQL to LINQ ... and over the years I always found Linq Pad as a very handy tool...
Finally I found the LINQ query that match my SQL statement:
from falta in db.Falta
join professor in db.Professor on falta.Id_profe equals professor.Id_profe
group new {professor, falta} by new {
professor.Llinatge,
professor.Nom
} into g
select new {
g.Key.Nom,
g.Key.Llinatge,
FJ = (System.Int64?)g.Sum(p => (
p.falta.Aprovada == true ? 1 : 0)),
FNJ = (System.Int64?)g.Sum(p => (
p.falta.Aprovada == false ? 1 : 0))
};
Thank you for your help! Hope this helps!
Related
How can I do this correctly?
This is failing because schedule-on does not exist within m from RR2.
var RR = (from m in DataContext.csrcallds
where m.scheduledon >= earliestDate
&& m.scheduledon <= objdate1.DateStart
&& m.assignto == 113
&& (SqlMethods.DateDiffDay(m.scheduledon, m.completedon) > 5)
select m
);
var RR2 = RR.Select(x => (GetBusinessDays((DateTime)x.scheduledon, (DateTime)x.completedon)) > 5).ToList());
var RnR = (from m in RR2
group m by new { m.scheduledon.Value.Year, m.scheduledon.Value.Month } into p
orderby p.Key.Year ascending, p.Key.Month ascending
select new Date1()
{
theDate = DateTime.Parse($"{p.Key.Month} - {p.Key.Year}"),
theCount = p.Count(),
theString = $"{p.Key.Month} - {p.Key.Year}"
});
I am trying to query all the results.
Then use my GetBusinessDay function to filter out the ones I don't need, gathering only the records within 5 business days.
Then put the results into my Model named Date1.
I'm trying to do it like this because I cannot use GetBusinessDays within an LINQ query.
So I'm trying to filter it outside of SQL, then group the records again.
How do I go about accomplishing this task?
You could add this to your SQL Query to filter out the weekend days.
SELECT *
FROM your_table
WHERE ((DATEPART(dw, date_created) + ##DATEFIRST) % 7) NOT IN (0, 1)
Or This
select [date_created]
from table
where DATENAME(WEEKDAY, [date_created]) <> 'Saturday'
and DATENAME(WEEKDAY, [date_created]) <> 'Sunday'
Or if you have to stick to LINQ try the ideas outlined here:
Linq query DateTime.Date.DayOfWeek
DateTime firstSunday = new DateTime(1753, 1, 7);
var bookings = from b in this.db.Bookings
where EntityFunctions.DiffDays(firstSunday, b.StartDateTime) % 7 == 1
select b;
Solved by using function workdays server side:
https://stackoverflow.com/a/252532/6157660
Allows me to make a simple LINQ query, and gives me what I need.
I did edit the function to remove the +1 from DateDiff. as same days should be 0 not 1.
Thank you guys for your help!
var RnR = (from m in DataContext.csrcallds
where m.scheduledon >= earliestDate
&& m.scheduledon <= objdate1.DateStart
&& m.assignto == 113
&& (DataContext.fn_WorkDays((DateTime)m.scheduledon, (DateTime)m.completedon)) > 5
group m by new { m.scheduledon.Value.Year, m.scheduledon.Value.Month } into p
orderby p.Key.Year ascending, p.Key.Month ascending
select new Date1()
{
theDate = DateTime.Parse($"{p.Key.Month} - {p.Key.Year}"),
theCount = p.Count(),
theString = $"{p.Key.Month} - {p.Key.Year}"
});
I need to convert an SQL query to Linq/Lambda expression, I am trying doing the same but not getting the desired results.
SQL:
SELECT b.*, n.notes
FROM Goal_Allocation_Branch as b
INNER JOIN Goal_Allocation_Product as g
on b.Product = g.ProductID
and b.Year = g.Year
left join Goal_Allocation_Branch_Notes as n
on b.branchnumber = n.branch
and n.year = ddlYear
WHERE b.Year = ddlYear
and g.Show = 1
and branchnumber = ddlBranch
I am new to Linq , I am getting error on Join Clause , and X is not containing any data from first Join
var result = (from br in _DB_Branches.Goal_Allocation_Branches
join pr in _DB_Product.Goal_Allocation_Products on new { br.Product, br.Year } equals new {Product= pr.ProductID, Year= pr.Year }
join n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(n => n.Year == ddlYear) on br.BranchNumber equals n.Branch into Notes
from x in Notes.DefaultIfEmpty()
select new BranchNotesViewModel
{
Year = x.Year,
BranchNumber = x.Branch,
ProductID = x.ProdID
}
).ToList();
Update: My First Join clause initially giving error "The type of one of the expression in Join Clause is incorrect " is resolved, when I Changed On Clause
from
"on new { br.Product, br.Year } equals new {pr.ProductID, pr.Year}"
"on new { br.Product, br.Year } equals new {Product=pr.ProductID,Year= pr.Year}"
still not getting desired results as expected from above SQL query. Please advise..
It should be something like this (see note):
var result =
(from br in _DB_Branches.Goal_Allocation_Branches
join pr in _DB_Product.Goal_Allocation_Products
on br.Product equals pr.ProductID
from n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(x=>
x.branch == br.branchnumber
&& x.year == ddlYear
).DefaultIfEmpty()
where
br.Year == ddlYear
&& and br.Year == pr.Year
&& pr.Show == 1
&& br.branchnumber == ddlBranch
select new BranchNotesViewModel
{
Year = ...,
BranchNumber = ...,
ProductID = ...
}
).ToList();
Note: Change the select, to the properties you want.
Edit: fixed some syntax errors.
I finally figured out the correct answer. Working absolutely fine
var result = (from br in _DB_Branches.Goal_Allocation_Branches
join pr in _DB_Product.Goal_Allocation_Products on new { br.Product, br.Year } equals new { Product = pr.ProductID, Year = pr.Year }
join n in _DB_Notes.Goal_Allocation_Branch_Notes.Where(n=>n.Year==ddlYear) on br.BranchNumber equals n.Branch into Notes
where br.Year==ddlYear
&& pr.Show== true
&& br.BranchNumber==ddlBranch
from x in Notes.DefaultIfEmpty()
select new BranchNotesViewModel
{
Year=x.Year,
BranchNumber=x.Branch,
ProductID=br.Product,
Notes = x.Notes,
//All other fields needed
}
).ToList();
I would like to use Average function with Count in my Linq to EF query. So if I have to explain what I try to realize with my code part in t-sql for more clear understanding, You can take look below them,
select s.SalesPointId, count(*) as ipp
from ScoreItem si
inner join Score s on s.Id = si.ScoreId
where si.ResearchGroupType = 0 and si.IsValidForSalesPoint = 1
group by s.SalesPointId
select avg(ipp)
from (
select s.SalesPointId, count(*) as ipp
from ScoreItem si
inner join Score s on s.Id = si.ScoreId
where si.ResearchGroupType = 0 and si.IsValidForSalesPoint = 1
group by s.SalesPointId
)
As a consequence I have wrote below code in Linq query,
List<CvmNameAndValue> AnatolianSalesHeadshipIPPScore = (from si in db.ScoreItem
join s in db.Score on si.ScoreId equals s.Id
join sp in db.SalesPoint on s.SalesPointId equals sp.Id
where (si.ResearchGroupType == ResearchGroupType.ScoreCard && si.IsValidForSalesPoint && sp.CompanyId == ContextData.User.CompanyId && s.ProjectPeriodId == ProjectPeriodId && spIds.Contains(sp.Id))
group s by s.SalesPointId into g
select new CvmNameAndValue
{
Name = SystemSetting.Label_AnatolianSalesHeadshipIPPScore,
Value = g.Average(x => db.Score.Count()).ToString()
})
.ToList();
retVal.Data.DataGroup = AnatolianSalesHeadshipIPPScore.ToList();
return retVal;
But, Unfortunately they didn't return same result for me, so if you have any suggestion about my logic mistakes, please feel to free and share with me,
Finally I have solved my problem, so if you need such as thing, it can be solve your problem,
double AnatolianSalesHeadshipIPPScore = 0;
AnatolianSalesHeadshipIPPScore = (from si in db.ScoreItem
join s in db.Score on si.ScoreId equals s.Id
join sp in db.SalesPoint on s.SalesPointId equals sp.Id
where (si.ResearchGroupType == ResearchGroupType.ScoreCard && si.IsValidForSalesPoint && sp.CompanyId == ContextData.User.CompanyId && s.ProjectPeriodId == ProjectPeriodId)
group si by s.SalesPointId into g
select new
{
sid = g.Key,
count = g.Count()
}).Average(m => m.count);
Hi i'm trying to convert this SQL script in Linq expression
but i donĀ“t know how do the MAX method in Linq
someone can help me?
thank you!
SELECT c.Nome,
c.NumeroRG,
f.Tipo,
f.Descricao,
f.DataHora,
f.IdCliente,
c.IdCliente,
f.IdFrequencia
FROM Cliente c, Frequencia f
WHERE f.Tipo = 1
AND c.IdCliente = f.IdCliente
AND cast(f.DataHora as date) = cast(getdate() as date)
AND f.IdFrequencia = (select MAX(fr.IdFrequencia)
from frequencia fr
where fr.IdCliente =c.IdCliente)
Perhaps something like this:
var query = from client in db.Cliente
join freq in db.Frequencia
on client.IdCliente equals freq.IdCliente
where freq.Tipo == 1
&& freq.DataHora.Date == DateTime.Now.Date
&& freq.IdFrequencia == db.Frequencia.Where(f => f.IdCliente == client.IdCliente)
Max(f => f.IdFrequencia)
select new { .... };
Maybe you need to replace DateTime.Now.Date/DateTime.Today with SqlFunctions.DatePart if you use LINQ-To-Entities, but you haven't mentioned that.
this worked well! thanks
var query = from client in db.Cliente
join freq in db.Frequencia
on client.IdCliente equals freq.IdCliente
where freq.Tipo == true
&& freq.DataHora.Value.Date == DateTime.Today.Date
&& freq.IdFrequencia == db.Frequencia.Where(f => f.IdCliente == client.IdCliente).Max(f => f.IdFrequencia)
select new { Nome = client.Nome, Descricao = freq.Descricao };
Im just new in MVC3 and have a little problem. I want to convert this SQL statement into Linq. Can anyone please help me with this problem, here is my sql Statement:
SELECT a.payment_ref_no,
c.institution_name,
a.check_date,
batchstatus = CASE
WHEN d.mccount = Count(b.check_detail_no) THEN
'Completed'
WHEN d.mccount IS NULL THEN 'Approved'
WHEN d.mccount < Count(b.check_detail_no) THEN
'Partially Processed'
END,
noofpayments=Count(b.check_detail_no),
totalamount=Sum(b.check_amount),
d.mccount
FROM check_request a
JOIN check_details b
ON a.request_ref_no = b.request_ref_no
JOIN institution c
ON a.company_code = c.company_code
LEFT JOIN vw_batchstatus d
ON a.request_ref_no = d.request_ref_no
WHERE a.payment_ref_no IS NOT NULL
GROUP BY a.payment_ref_no,
a.check_date,
c.institution_name,
d.mccount
Done mostly from memory, may be some issues, but should be a step in the right direction for you.
var test = from a in check_request
join b in check_details on a.request_ref_no equals b.request_ref_no
join c in institution on a.company_code equals c.company_code
join d in vw_batchstatus on a.request_ref_no equals d.request_ref_no into dvwinner
from d in dvwinner.DefaultIfEmpty()
where a.payment_ref.HasValue
group a by new (a.payment_ref_no, a.check_date, c.institution_name, d.mccount) into gr1
select new {
ref_no = a.payment_ref_no,
inst_name = c.institution_name,
check_date = a.check_date,
batstat = !d.mccount.HasValue ? 'Approved' : d.mccount == b.check_detail_no.Count() ? 'Completed' : 'Partially Processed',
noofpayments = b.check_detail_no.Count(),
ttlamount = gr1.Sum(p=>p.check_amount),
mccount = d.mccount
};
Thanks Kyle for the help.I finally solved my own problems, here is the linq of my sql statement
var test = from a in CHECK_REQUESTs
join b in CHECK_DETAILS on a.REQUEST_REF_NO equals b.REQUEST_REF_NO
join c in INSTITUTIONs on a.COMPANY_CODE equals c.COMPANY_CODE
join d in Vw_BatchStatus on a.REQUEST_REF_NO equals d.REQUEST_REF_NO into t from rt in t.DefaultIfEmpty()
where a.PAYMENT_REF_NO != string.Empty
let institutionName = (string)c.Institution_Name
let mcCount = (int)rt.Mccount
group b by new
{
a.PAYMENT_REF_NO,
a.Check_Date,
institutionName,
mcCount
} into gr1
select new
{
gr1.Key.PAYMENT_REF_NO,
gr1.Key.institutionName,
gr1.Key.Check_Date,
batchstatus = (gr1.Key.mcCount == gr1.Count()) ? "Completed" :
(gr1.Key.mcCount < gr1.Count()) ? "Partially Processed":
(gr1.Key.mcCount == null ) ? "Approved" : " ",
noofpayments = gr1.Count(),
totalamount = gr1.Sum(c => c.Check_Amount)
};