SQL:
SELECT
p.PipelineID
, MAX(PipelineJobStatus.CreatedTimeStamp)
, Client.ClientName
, FCO.NameFCO
, p.ProjectValueHr
, p.ProjectValueMoney
, p.CommentPipeline
, PipelineJobStatus.CreatedTimeSTamp
, p.ModifiedTimeStamp
, Employee.Name
, Employee.Surname
, JobStatus.JobStatusName
FROM (Pipeline p
LEFT OUTER JOIN PipelineJobStatus ON p.PipelineID = PipelineJobStatus.PipelineID)
INNER JOIN JobStatus ON (PipelineJobStatus.JobStatusID = JobStatus.JobStatusID)
LEFT OUTER JOIN Client ON (p.ClientID = Client.ClientID)
LEFT OUTER JOIN FCO ON (p.FCOID = FCO.FCOID)
LEFT OUTER JOIN Employee ON (p.CreatedBy = Employee.EmployeeD)
WHERE PipelineJobStatus.CreatedTimeStamp IN
(SELECT MAX(CreatedTimeStamp) FROM PipelineJobStatus GROUP BY PipelineID)
GROUP BY p.PipelineID
, Client.ClientName
, FCO.NameFCO
, p.ProjectValueHr
, p.ProjectValueMoney
, p.CommentPipeline
, PipelineJobStatus.CreatedTimeSTamp
, p.ModifiedTimeStamp
, Employee.Name
, Employee.Surname
, JobStatus.JobStatusName
I've tried LINQ:
from pjs in db.PipelineJobStatus
//.OrderByDescending(p=>p.CreatedTimeStamp)
//.DistinctBy(p => p.PipelineID)
//.FirstOrDefault()
from pipe in db.Pipelines
.Where(pipe => pipe.PipelineID == pjs.PipelineID).DefaultIfEmpty()
from status in db.JobStatus
.Where(statuses => statuses.JobStatusID == pjs.JobStatusID)
.DefaultIfEmpty()
from fco in db.FCOes
.Where(fcoes => fcoes.FCOID == pipe.FCOID)
from client in db.Clients
.Where(clients => clients.ClientID == pipe.ClientID)
//Where PipelineJobStatus.CreatedTimeStamp in (select max(CreatedTimeStamp) from PipelineJobStatus group by PipelineID)
.Where(pjs.CreatedTimeStamp in select Max(pjs.CreatedTimeStamp)from PipelineJobStatus group by)
group by { pipe.PipelineID } //group new
by new
{
status.JobStatusName,
pipe.PipelineID,
pipe.ClientID,
client.ClientName,
fco.NameFCO,
fco.FCOID,
pipe.Employee.Name,
pipe.Employee.Surname,
pipe.CommentPipeline,
pipe.CreatedBy,
pipe.CreatedTimeStamp,
pipe.ModifiedTimeStamp,
pipe.ProjectValueHr,
pipe.ProjectValueMoney
} into g
orderby g.Key.PipelineID descending
select new StatusPipelineMerge
{
PipelineID = g.Key.PipelineID,
ProjectValueHr = g.Key.ProjectValueHr,
ProjectValueMoney = g.Key.ProjectValueMoney,
CommentPipeline = g.Key.CommentPipeline,
ClientName = g.Key.ClientName,
FCOName = g.Key.NameFCO,
FCOID = g.Key.FCOID,
ClientID = g.Key.ClientID,
CreatedTimeStamp = g.Key.CreatedTimeStamp,
ModifiedTimeStamp = g.Key.ModifiedTimeStamp,
CreatedBy = g.Key.CreatedBy,
//CreatedNameSurname = g.Key.Employee.Name + " " + g.Key.Employee.Surname
JobStatusName = g.Key.JobStatusName
}
.Where() clause is underlined with red..
Where I am wrong?
P.S. SQL is working
I will change this chained tables, with joins, for now I just want to work.
Maybe store procedure is not lousy option here.
Related
I am working with some SQL that has been provided and I am running into an issue where the count in the LINQ is different from the count in the SQL and would appreciate some help if possible.
The original SQL that was given is pretty poorly arranged and has a large number of nested queries. This being one of them. I have broken the query down into its main component and am now stitching it back together with LINQ.
The SQL that I am working with is here :
DECLARE #QSCollectionId UNIQUEIDENTIFIER = 'f52ec043-b360-4266-f95f-08d7c66074pe';
SELECT fieldid
Count(fieldid) AS fieldcount,
Sum(CASE
WHEN answer = [value] AND Answer IS NOT NULL THEN 1
ELSE 0
END) AS FieldAnswerMatchCount
FROM (SELECT DISTINCT FCI.fieldid,
answer,
QSA.qsrid,
FAG.fieldid AS dependentfield,
FAG.value
FROM forms.fieldconstraints FCI
INNER JOIN forms.sectionfieldmappings SFM
ON FCI.fieldid = SFM.fieldid
INNER JOIN forms.qssectionmappings QSSM
ON SFM.sectionid = QSSM.sectionid
INNER JOIN sessions.qsr
ON QSSM.qsid = qsr.qsid
--AND Qsr.QSCollectionId=#QSCollectionId
LEFT JOIN forms.answerguides FAG
ON
FCI.dependantanswerguideid = FAG.answerguideid
LEFT JOIN sessions.qsranswers QSA
ON FAG.fieldid = QSA.fieldid
AND Qsr.QsrId = QSA.qsrid
) AS
FieldConstr
GROUP BY fieldid
The LINQ
var id = Guid.Parse("f52ec043-b360-4266-f95f-08d7c66074be");
var firstResultPartThree = (from fci in FieldConstraints
join sfm in SectionFieldMappings on fci.FieldId equals sfm.FieldId
join qssm in QSSectionMappings on sfm.SectionId equals qssm.SectionId
join qsr in QSRs on new { qssm.QSId } equals new { qsr.QSId }
join ag in AnswerGuides on fci.DependantAnswerGuideId equals ag.AnswerGuideId into agResult
from agJoin in agResult.DefaultIfEmpty()
join qsrAnswers in QSRAnswers on new { agJoin.FieldId, qsr.QsrId } equals new {qsrAnswers.FieldId, qsrAnswers.QsrId} into qsrAnswersResult
from qsrAnswersJoin in qsrAnswersResult.DefaultIfEmpty()
//where qsr.QSCollectionId == id
select new {
FieldId = fci.FieldId,
Answer = qsrAnswersJoin.Answer,
QsrId = (Guid?)qsrAnswersJoin.QsrId,
DependentFieldId = agJoin.FieldId,
Value = agJoin.Value
}
);
firstResultPartThree.Dump();
var firstResultPartTwo = (from fr in firstResultPartThree
where fr.FieldId == Guid.Parse("98CA6B6F-4070-4CEB-E9F1-08D7C66278F9")
group fr by fr.FieldId into grp
select new {
FieldId = grp.Key,
Fieldcount = grp.Count(),
FieldAnswerMatchCount = grp.Count(x => (Guid?)grp.Key.Value != null)
}
);
The result of the LINQ in the example below gives me
FieldId | fieldcount | FieldAnswerMatchCount
98ca6b6f-4070-4ceb-e9f1-08d7c66278f9 | 4 | 4 |
The result of the sql for the same data is
98ca6b6f-4070-4ceb-e9f1-08d7c66278f9 | 3 | 2 |
The area that I am struggling with is
select new {
FieldId = grp.Key,
Fieldcount = grp.Count(),
FieldAnswerMatchCount = grp.Count(x => (Guid?)grp.Key.Value != null)
I understand that the count in the select is wrong, however I do not know how I need to correct it and would be grateful for some help.
I'm trying to rewrite sql query to linq but can't do it myself.
The most problem for me is to get I,II and III aggregated values.
Sql query:
select o.Name,t.TypeID, SUM(e.I),SUM(e.II),SUM(e.III) from Expenditure e
join Finance f on f.FinanceId = e.FinanceId
join FinanceYear fy on fy.FinanceYearId = f.FinanceYearId and fy.StatusId = 1
join Project p on p.ProjectId = fy.ProjectId
join Organization o on o.OrganizationId = p.OrganizationId
join Type t on t.TypeID = p.TypeID
where fy.Year = 2018
group by o.Name,s.TypeID
and what I have done so far is:
var x = (from e in _db.Expenditures
join f in _db.Finances on e.FinanceId equals f.FinanceId
join fy in _db.FinanceYears on f.FinanceYearId equals fy.FinanceYearId and fy.StatusId = 1 // this does not work, cant join on multiple conditions?
join p in _db.Projects on fy.ProjectId equals p.ProjectId
join o in _db.Organizations on p.OrganizationId equals o.OrganizationId
join s in _db.Types on p.TypeId equals s.TypeId
group new { o, s } by new { o.OrganizationId, s.TypeId }
into grp
select new AggModel
{
OrganizationId = grp.Key.OrganizationId,
TypeId = grp.Key.TypeId,
I = ?,
II = ?,
III = ?,
}
);
Try something like this:
group new { e, o, s } by new { o.OrganizationId, s.TypeId }
into grp
select new AggModel
{
OrganizationId = grp.Key.OrganizationId,
TypeId = grp.Key.TypeId,
I = grp.Sum(a => a.e.I),
II = grp.Sum(a => a.e.II),
III = grp.Sum(a => a.e.III),
}
You'll need to adjust the right side of the lambda to navigate to the correct property.
You Need to use the Group by for aggregation methods.
Check the below link for more Knowledge.
How to use aggregate functions in linq with joins?
var response = ( from e in db.tblEvents
join f in db.tblEventTypes on e.FightTypeId equals f.eventTypeId
into egroup
from e in egroup.DefaultIfEmpty()
join w in db.tblUserWebApp on e.ModifiedUserId equals w.Id
orderby e.LastUserModified descending
select new {
FightTypeName = f.eventTypeName,
EventID = e.EventID,
FightTypeId=e.FightTypeId,
Title = e.Title,
Date = e.Date,
Location = e.Location,
UserSelectFavoriteFlag =e.UserSelectFavoriteFlag ,
Price=e.Price,
UserPredictionFlag=e.UserPredictionFlag,
PredictionStartDate= e.PredictionStartDate ,
PredictionEndDate = e.PredictionEndDate,
ModifiedUserId = w.Id,
ModifiedUser = w.LoginName,
LastUserModified = e.LastUserModified,
});
return Ok(response);
how can i use left outer join since i have 3 table to join and i want to get all data from tblEvents table
Try this query
var response = ( from e in db.tblEventTypes
from f in db.tblEvents.where(x=>x.FightTypeId ==e.eventTypeId).DefaultIfEmpty()
from w in db.tblUserWebApp.where(x=>x.Id==f.ModifiedUserId)
orderby f.LastUserModified descending
select new {
FightTypeName = e.eventTypeName,
EventID = f.EventID,
FightTypeId=f.FightTypeId,
Title = f.Title,
Date = f.Date,
Location = f.Location,
UserSelectFavoriteFlag =f.UserSelectFavoriteFlag ,
Price=f.Price,
UserPredictionFlag=f.UserPredictionFlag,
PredictionStartDate= f.PredictionStartDate ,
PredictionEndDate = f.PredictionEndDate,
ModifiedUserId = w.Id,
ModifiedUser = w.LoginName,
LastUserModified = f.LastUserModified,
});
I need to convert following SQL into LINQ
select
app.id,
app.name,
app.version,
s.application,
s.analysis,
s.behaviour,
(select count(ia.id)
from appInstalled ia
JOIN deviceUser ud ON ia.device_id = ud.device_id
where ia.app_id = app.id) as deviceCount,
max(alrt.alert_date)
from application app
left join score s on app.app_md5 = s.md5hash
left join alert alrt on app.id = alrt.app_id
where app.name like '%gpsnav%'
group by device;
This is what I've done so far
var appQuery = (from app in entities.applications
join score in entities.scores on app.app_md5 equals score.md5hash into appScore
join alrt in entities.alerts on app.id equals alrt.app_id into appAlerts
from s in appScore.DefaultIfEmpty()
from a in appAlerts.DefaultIfEmpty()
let deviceCount = (from iapp in entities.appInstalled
join ud in entities.deviceUser on iapp.device_id equals ud.device_id
where iapp.id == app.id
select iapp.id).Count()
where string.IsNullOrEmpty(searchTerm) || app.name.ToLower().Contains(searchTerm.ToLower())
select new
{
AppId = app.id,
AppName = app.name,
AppVersion = app.version,
AppScore = s.application,
Analysis = s.analysis,
Behavior = s.behaviour,
Devices = deviceCount,
AlertDate = a.alert_date
});
var grouped = from a in appQuery
group a by new
{
a.AppId,
a.AppName,
a.AppVersion,
a.AppScore,
a.Analysis,
a.Behavior,
a.Devices,
a.AlertDate
} into g
select new
{
g.Key.AppId,
g.Key.AppName,
g.Key.AppVersion,
g.Key.AppScore,
g.Key.Analysis,
g.Key.Behavior,
g.Key.Devices,
AlertDate = g.Max(x=>x.AlertDate)
};
The above LINQ works but the data is incorrect for Device and AlertDate. What I am missing in here? Also I am not getting max of AlertDate while grouping in LINQ.
I try to translate this SQL code :
SELECT w.Id, w.LastName, w.FirstName, SUM(d.Price*dt.Number) AS somme
FROM Waiter w
INNER JOIN Client c on w.Id = c.WaiterId
INNER JOIN DisheOnTable dt on c.Id = dt.ClientId
INNER JOIN Dishe d on dt.DisheId = d.Id
GROUP BY w.Id, w.LastName, w.FirstName
ORDER BY somme DESC;
in entity framework.
I tried something like this
var query2 = (from w in db.Waiter
join c in db.Client on w.Id equals c.WaiterId
join dt in db.DisheOnTable on c.Id equals dt.ClientId
join d in db.Dishe on dt.DisheId equals d.Id
group w by new { w.Id, w.LastName, w.FirstName } into g
//orderby g.Select() descending
select new
{
id = g.Key.Id,
lastname = g.Key.LastName,
firstname = g.Key.FirstName,
total = g.Sum(q => q.)
});
but my sum doesn't work (after multiple research and try) and i don't know how to multiply my variables.
PS : The SQL statement works well, i tried it.
Thank you for helping guys ! :)
You need to group on both dish and DishOnTable alias as Price is in Dish and Number is in DishOnTable:
group new{ d,dt} by new {w.Id, w.LastName, w.FirstName} into g
and now sum the columns which you want from it
select new {
id = g.Key.Id,
lastname = g.Key.LastName,
firstname = g.Key.FirstName,
total = g.Sum(q => q.d.Price * q.dt.Number)
}).OrderBy(x=>x.total)