left join do not show all records - visual-studio-2010

In following code left join do not show all the records from left !!!
select *,CASE WHEN (ResDEBIT> ResCREDIT) THEN (ResDEBIT) when (ResCREDIT> ResDEBIT)then (ResCREDIT) else 0 END AS Mande,CASE WHEN (ResDEBIT> ResCREDIT) THEN ('debit') when (ResCREDIT> ResDEBIT)then ('credit') ELSE ('ziro') END AS Status from(SELECT Sales.CustomerInfo.CustomerInfoID,FullTitle=(cast(Sales.CustomerInfo.AccountFK as nvarchar)+' - '+Sales.CustomerInfo.FullName), Sales.CustomerInfo.TopicFK, Sales.CustomerInfo.AccountFK,Sales.CustomerInfo.CompanyRegNo,Sales.CustomerInfo.PersonTypeFK,Sales.CustomerInfo.BankAccountDetail,Sales.CustomerInfo.BankAccountNo, Sales.CustomerInfo.AccountNo, Sales.CustomerInfo.FullName,
Sales.CustomerInfo.Birthdate, Sales.CustomerInfo.TitleFK, Sales.CustomerInfo.RegistrationDate, Sales.CustomerInfo.CustomerPhotoFK, Sales.CustomerInfo.SocialNo,
Sales.CustomerInfo.WebPage, Sales.CustomerInfo.JobFK, Sales.CustomerInfo.MaxDebitLimit, Sales.CustomerInfo.MaxChequeCredit,
Sales.CustomerInfo.PreferedPaymentMethodFK, Sales.CustomerInfo.FirstBalanceKind, Sales.CustomerInfo.FirstBalance, Sales.CustomerInfo.Debit,
Sales.CustomerInfo.Credit, Sales.CustomerInfo.Note, Sales.CustomerInfo.FinancialPeriodFK, Sales.CustomerInfo.CompanyInfoFK,
isnull(SUM(Accounting.DocumentDetail.Debit),0) AS Debit1, isnull(SUM(Accounting.DocumentDetail.Credit),0) AS Credit1, (CASE WHEN (isnull(SUM(Accounting.DocumentDetail.Credit),0)
- isnull(SUM(Accounting.DocumentDetail.Debit),0)) < 0 THEN (isnull(SUM(Accounting.DocumentDetail.Debit),0) - isnull(SUM(Accounting.DocumentDetail.Credit),0)) ELSE 0 END) AS ResDEBIT,
(CASE WHEN (isnull(SUM(Accounting.DocumentDetail.Credit),0) - isnull(SUM(Accounting.DocumentDetail.Debit),0)) > 0 THEN (isnull(SUM(Accounting.DocumentDetail.Credit),0)
- isnull(SUM(Accounting.DocumentDetail.Debit),0)) ELSE 0 END) AS ResCREDIT,Sales.CustomerInfo.BlackListed, Sales.CustomerInfo.IsActive
FROM Sales.CustomerInfo left JOIN
Accounting.DocumentDetail ON Sales.CustomerInfo.AccountFK = Accounting.DocumentDetail.TopicFK
GROUP BY Sales.CustomerInfo.CustomerInfoID, Sales.CustomerInfo.TopicFK, Sales.CustomerInfo.AccountFK, Sales.CustomerInfo.AccountNo,
Sales.CustomerInfo.FullName, Sales.CustomerInfo.Birthdate, Sales.CustomerInfo.TitleFK,Sales.CustomerInfo.CompanyRegNo,Sales.CustomerInfo.PersonTypeFK,Sales.CustomerInfo.BankAccountDetail,Sales.CustomerInfo.BankAccountNo, Sales.CustomerInfo.RegistrationDate,
Sales.CustomerInfo.CustomerPhotoFK, Sales.CustomerInfo.SocialNo, Sales.CustomerInfo.WebPage, Sales.CustomerInfo.JobFK, Sales.CustomerInfo.MaxDebitLimit,
Sales.CustomerInfo.MaxChequeCredit, Sales.CustomerInfo.PreferedPaymentMethodFK, Sales.CustomerInfo.FirstBalanceKind, Sales.CustomerInfo.FirstBalance,
Sales.CustomerInfo.Debit, Sales.CustomerInfo.Credit, Sales.CustomerInfo.Note, Sales.CustomerInfo.FinancialPeriodFK, Sales.CustomerInfo.CompanyInfoFK,
Sales.CustomerInfo.BlackListed, Sales.CustomerInfo.IsActive) CustomerInfo

check how many distinct record exists for your group by columns
Select distinct
Sales.CustomerInfo.CustomerInfoID
,Sales.CustomerInfo.TopicFK
,Sales.CustomerInfo.AccountFK
,Sales.CustomerInfo.AccountNo
,Sales.CustomerInfo.FullName
,Sales.CustomerInfo.Birthdate
,Sales.CustomerInfo.TitleFK
,Sales.CustomerInfo.CompanyRegNo
,Sales.CustomerInfo.PersonTypeFK
,Sales.CustomerInfo.BankAccountDetail
,Sales.CustomerInfo.BankAccountNo
,Sales.CustomerInfo.RegistrationDate
,Sales.CustomerInfo.CustomerPhotoFK
,Sales.CustomerInfo.SocialNo
,Sales.CustomerInfo.WebPage
,Sales.CustomerInfo.JobFK
,Sales.CustomerInfo.MaxDebitLimit
,Sales.CustomerInfo.MaxChequeCredit
,Sales.CustomerInfo.PreferedPaymentMethodFK
,Sales.CustomerInfo.FirstBalanceKind
,Sales.CustomerInfo.FirstBalance
,Sales.CustomerInfo.Debit
,Sales.CustomerInfo.Credit
,Sales.CustomerInfo.Note
,Sales.CustomerInfo.FinancialPeriodFK
,Sales.CustomerInfo.CompanyInfoFK
,Sales.CustomerInfo.BlackListed
,Sales.CustomerInfo.IsActive
from Sales.CustomerInfo
the number of return records for your above query will be same...To get all records from your left table you can use any one of the below 2 methods but i would prefer the 2nd one
1)use sub query
2)first do your aggregation in a separate query and join it with your left table again... the query should be some thing similar to below code:
;WITH CTE ( AccountFK, Debit1 ,Credit1 ,ResDEBIT ,ResCREDIT )
AS (
SELECT
Sales.CustomerInfo.AccountFK
,isnull(SUM(Accounting.DocumentDetail.Debit), 0) AS Debit1
,isnull(SUM(Accounting.DocumentDetail.Credit), 0) AS Credit1
,(
CASE
WHEN (isnull(SUM(Accounting.DocumentDetail.Credit), 0) - isnull(SUM(Accounting.DocumentDetail.Debit), 0)) < 0
THEN (isnull(SUM(Accounting.DocumentDetail.Debit), 0) - isnull(SUM(Accounting.DocumentDetail.Credit), 0))
ELSE 0
END
) AS ResDEBIT
,(
CASE
WHEN (isnull(SUM(Accounting.DocumentDetail.Credit), 0) - isnull(SUM(Accounting.DocumentDetail.Debit), 0)) > 0
THEN (isnull(SUM(Accounting.DocumentDetail.Credit), 0) - isnull(SUM(Accounting.DocumentDetail.Debit), 0))
ELSE 0
END
) AS ResCREDIT
FROM Sales.CustomerInfo
LEFT JOIN Accounting.DocumentDetail ON Sales.CustomerInfo.AccountFK = Accounting.DocumentDetail.TopicFK
GROUP BY Sales.CustomerInfo.CustomerInfoID
,Sales.CustomerInfo.TopicFK
,Sales.CustomerInfo.AccountFK
,Sales.CustomerInfo.AccountNo
,Sales.CustomerInfo.FullName
,Sales.CustomerInfo.Birthdate
,Sales.CustomerInfo.TitleFK
,Sales.CustomerInfo.CompanyRegNo
,Sales.CustomerInfo.PersonTypeFK
,Sales.CustomerInfo.BankAccountDetail
,Sales.CustomerInfo.BankAccountNo
,Sales.CustomerInfo.RegistrationDate
,Sales.CustomerInfo.CustomerPhotoFK
,Sales.CustomerInfo.SocialNo
,Sales.CustomerInfo.WebPage
,Sales.CustomerInfo.JobFK
,Sales.CustomerInfo.MaxDebitLimit
,Sales.CustomerInfo.MaxChequeCredit
,Sales.CustomerInfo.PreferedPaymentMethodFK
,Sales.CustomerInfo.FirstBalanceKind
,Sales.CustomerInfo.FirstBalance
,Sales.CustomerInfo.Debit
,Sales.CustomerInfo.Credit
,Sales.CustomerInfo.Note
,Sales.CustomerInfo.FinancialPeriodFK
,Sales.CustomerInfo.CompanyInfoFK
,Sales.CustomerInfo.BlackListed
,Sales.CustomerInfo.IsActive
)
SELECT Sales.CustomerInfo.CustomerInfoID
,FullTitle = (cast(Sales.CustomerInfo.AccountFK AS NVARCHAR) + ' - ' + Sales.CustomerInfo.FullName)
,Sales.CustomerInfo.TopicFK
,Sales.CustomerInfo.AccountFK
,Sales.CustomerInfo.CompanyRegNo
,Sales.CustomerInfo.PersonTypeFK
,Sales.CustomerInfo.BankAccountDetail
,Sales.CustomerInfo.BankAccountNo
,Sales.CustomerInfo.AccountNo
,Sales.CustomerInfo.FullName
,Sales.CustomerInfo.Birthdate
,Sales.CustomerInfo.TitleFK
,Sales.CustomerInfo.RegistrationDate
,Sales.CustomerInfo.CustomerPhotoFK
,Sales.CustomerInfo.SocialNo
,Sales.CustomerInfo.WebPage
,Sales.CustomerInfo.JobFK
,Sales.CustomerInfo.MaxDebitLimit
,Sales.CustomerInfo.MaxChequeCredit
,Sales.CustomerInfo.PreferedPaymentMethodFK
,Sales.CustomerInfo.FirstBalanceKind
,Sales.CustomerInfo.FirstBalance
,Sales.CustomerInfo.Debit
,Sales.CustomerInfo.Credit
,Sales.CustomerInfo.Note
,Sales.CustomerInfo.FinancialPeriodFK
,Sales.CustomerInfo.CompanyInfoFK
,cte.Debit1
,cte.Credit1
,cte.ResDEBIT
,cte.ResCREDIT
,Sales.CustomerInfo.BlackListed
,Sales.CustomerInfo.IsActive
,CASE
WHEN (ResDEBIT > ResCREDIT)
THEN (ResDEBIT)
WHEN (ResCREDIT > ResDEBIT)
THEN (ResCREDIT)
ELSE 0
END AS Mande
,CASE
WHEN (ResDEBIT > ResCREDIT)
THEN ('debit')
WHEN (ResCREDIT > ResDEBIT)
THEN ('credit')
ELSE ('ziro')
END AS STATUS
FROM Sales.CustomerInfo
LEFT JOIN cte ON Sales.CustomerInfo.AccountFK = cte.AccountFK

Related

LINQ - Previous Record

All:
Lets say I have the following table:
RevisionID, Project_ID, Count, Changed_Date
1 2 4 01/01/2016: 01:02:01
2 2 7 01/01/2016: 01:03:01
3 2 8 01/01/2016: 01:04:01
4 2 3 01/01/2016: 01:05:01
5 2 15 01/01/2016: 01:06:01
I am ordering the records based on Updated_Date. A user comes into my site and edits record (RevisionID = 3). For various reasons, using LINQ (with entity framework), I need to get the previous record in the table, which would be RevisionID = 2 so I can perform calculations on "Count". If user went to edit record (RevisionID = 4), I would need to select RevisionID = 3.
I currently have the following:
var x = _db.RevisionHistory
.Where(t => t.Project_ID == input.Project_ID)
.OrderBy(t => t.Changed_Date);
This works in finding the records based on the Project_ID, but how then do I select the record before?
I am trying to do the following, but in one LINQ statement, if possible.
var itemList = from t in _db.RevisionHistory
where t.Project_ID == input.Project_ID
orderby t.Changed_Date
select t;
int h = 0;
foreach (var entry in itemList)
{
if (entry.Revision_ID == input.Revision_ID)
{
break;
}
h = entry.Revision_ID;
}
var previousEntry = _db.RevisionHistory.Find(h);
Here is the correct single query equivalent of your code:
var previousEntry = (
from r1 in db.RevisionHistory
where r1.Project_ID == input.Project_ID && r1.Revision_ID == input.Revision_ID
from r2 in db.RevisionHistory
where r2.Project_ID == r1.Project_ID && r2.Changed_Date < r1.Changed_Date
orderby r2.Changed_Date descending
select r2
).FirstOrDefault();
which generates the following SQL query:
SELECT TOP (1)
[Project1].[Revision_ID] AS [Revision_ID],
[Project1].[Project_ID] AS [Project_ID],
[Project1].[Count] AS [Count],
[Project1].[Changed_Date] AS [Changed_Date]
FROM ( SELECT
[Extent2].[Revision_ID] AS [Revision_ID],
[Extent2].[Project_ID] AS [Project_ID],
[Extent2].[Count] AS [Count],
[Extent2].[Changed_Date] AS [Changed_Date]
FROM [dbo].[RevisionHistories] AS [Extent1]
INNER JOIN [dbo].[RevisionHistories] AS [Extent2] ON [Extent2].[Project_ID] = [Extent1].[Project_ID]
WHERE ([Extent1].[Project_ID] = #p__linq__0) AND ([Extent1].[Revision_ID] = #p__linq__1) AND ([Extent2].[Changed_Date] < [Extent1].[Changed_Date])
) AS [Project1]
ORDER BY [Project1].[Changed_Date] DESC
hope I understood what you want.
Try:
var x = _db.RevisionHistory
.FirstOrDefault(t => t.Project_ID == input.Project_ID && t.Revision_ID == input.Revision_ID -1)
Or, based on what you wrote, but edited:
_db.RevisionHistory
.Where(t => t.Project_ID == input.Project_ID)
.OrderBy(t => t.Changed_Date)
.TakeWhile(t => t.Revision_ID != input.Revision_ID)
.Last()

Query Optimization - Suggestions?

I am hoping someone can help me understand this XML Showplan for a long running query. This query comes from a Crystal Report developed by the software vendor that is very slow running, and I'm trying to convert it to an SSRS report while speeding the query up.
Here is a link to the Execution Plan - File hosted on File Dropper.
And here is the actual query itself:
Select Distinct
CD.desclong [Center],
CD.CenterType,
Sub.Description [SubCenter],
Org.Description [OrgCenter],
CO.CodeID [CenterC],
Sub.CodeID [SubCenterC],
Org.CodeID [OrgCenterC],
Reg.Description [Region],
Reg.CodeID [RegionC],
Rec.CodeID [RecID],
Rec.Description [RecName],
Rec.NickName [RecNickName],
Acct.AccountID [AcctCharCode],
DM.DriveID,
DM.ExternalID [DriveExtID],
DM.FromDateTime [DriveDate],
dbo.getShiftProductProjectionList(DSD.shiftid) [ProductProjections],
dbo.getShiftProcedureProjectionList(DSD.shiftid) [ProcedureProjections],
dbo.getShiftMobileList(DSD.shiftid, '1,2,3') [MobileSetups],
LD.LocationName [LocationName],
Case DM.OwnerType
When 1 Then FSM.DisplayName
When 0 Then Acct.InternalName
End [OwnerName], Acct.ExternalID [AcctExtID], SM.ExternalID [SiteExtID],
Stat.StatusText [DriveStatus],
DSD.ShiftID,
DSD.ShiftStart,
DSD.ShiftEnd,
DT.EarlyShiftStart,
DT.LateShiftEnd,
Changes.*,
dbo.getOriginalProcedureProjection(Changes.dsprocshiftid, Changes.dsprocprocedureid) [OriginalProjection],
(Select Top 1 DescMed From Production.[dbo].QuickCodes where CodeValue = 'ACTEXTIDTAG') [ActExtIDTag],
(Select Top 1 DescMed From Production.[dbo].QuickCodes where CodeValue = 'SITEEXTIDTAG') [SiteExtIDTag],
(Select Top 1 DescMed From Production.[dbo].QuickCodes where CodeValue = 'DRVEXTIDTAG') [DrvExtIDTag],
Case When (Changes.TableName = 'DriveShiftProcedureDetail') Then (Select Top 1 projectionid From driveshiftproceduredetail where uniquekey = Changes.owneruniquekey) else null end as ProjectionID
From
Production.[dbo].rpt_DriveMaster DM
Join Production.[dbo].rpt_DriveShiftDetail DSD on DSD.DriveID = DM.DriveID
Join Production.[dbo].CriticalDriveChanges Changes on (Changes.SourceDriveID = DM.DriveID and Changes.SourceShiftID = DSD.ShiftID and
Production.[dbo].returnDateTime(year(Changes.ChangeWhen),month(Changes.ChangeWhen),day(Changes.ChangeWhen)) between '01/04/2015' and '01/04/2015')
And
(
(
(Changes.TableName='DriveShiftProcedureDetail' and Changes.ColumnName='projection')
or
(Changes.TableName='DriveShiftDetail' and (Changes.ColumnName='ShiftStart' or Changes.ColumnName='ShiftEnd'))
or
(Changes.TableName='DriveShiftDetail' and Changes.ColumnName='StaffRequested')
or
(Changes.TableName='DriveShiftDetail' and Changes.changetype='Delete')
or
(Changes.TableName='DriveMaster' and Changes.ColumnName='StatusID' and Changes.NewValue='5')
or
(Changes.TableName='DriveMaster' and Changes.ColumnName='FromDateTime')
or
(Changes.TableName='DriveShiftRoleTimeDetail' and Changes.ColumnName='Lead')
or
(Changes.TableName='DriveShiftRoleTimeDetail' and Changes.ColumnName='TravelTo')
or
(Changes.TableName='DriveShiftRoleTimeDetail' and Changes.ColumnName='Setup')
or
(Changes.TableName='DriveShiftRoleTimeDetail' and Changes.ColumnName='Breakdown')
or
(Changes.TableName='DriveShiftRoleTimeDetail' and Changes.ColumnName='TravelFrom')
or
(Changes.TableName='DriveShiftRoleTimeDetail' and Changes.ColumnName='WrapUp')
)
and
(Changes.ChangeWho<>'RMADMIN')
)
Join Production.[dbo].rpt_DriveStatusDef Stat on Stat.StatusID = DM.StatusID
Join Production.[dbo].DriveTimes DT on DT.DriveID = DM.DriveID
Left Outer Join Production.[dbo].rpt_CenterDetail CD on CD.CenterID = DM.centerid
Left Outer Join Production.[dbo].IDViewRegion Reg on CD.Region = Reg.CodeID
Left Outer Join Production.[dbo].IDViewOrgCenter Org on CD.OrgCenter = Org.CodeID
Left Outer Join Production.[dbo].IDViewOrgSubCenter Sub on CD.OrgSubcenter = Sub.CodeID
Left Outer Join Production.[dbo].IDViewCollectionOp CO on cd.centerid = CO.CodeID
Left Outer Join Production.[dbo].IDViewRecruiter Rec on Rec.CodeID = DM.RecruiterID
Left Outer Join Production.[dbo].rpt_Accounts Acct on Acct.AccountID = DM.AccountID
Left Outer Join Production.[dbo].rpt_FixedSiteScheduleMaster FSM on FSM.DrawID = DM.DrawID
Left Outer Join Production.[dbo].rpt_LocationDetail LD on LD.LocationID = DM.LocationID
Join Production.[dbo].rpt_SiteMaster SM on SM.SiteID = DM.SiteID
Where
(dbo.returnDateTime(year(DM.Fromdatetime),month(DM.Fromdatetime),day(DM.Fromdatetime)) between '01/04/2015' and '01/04/2015')
or (dbo.returnDateTime(year(Changes.previousdrivedate),month(Changes.previousdrivedate),day(Changes.previousdrivedate)) between '01/04/2015' and '01/04/2015')
Here is the actual execution plan using Set Statistics XML On
Execution Plan
Thanks!
I removed the functions for returnDateTime and used the following instead:
-- In the FROM statement
Join Hemasphere_Dev.[dbo].CriticalDriveChanges Changes on (Changes.SourceDriveID = DM.DriveID And Changes.SourceShiftID = DSD.ShiftID And Changes.ChangeWhen Between '01/01/2015' And '01/15/2015')
--Hemasphere_Dev.[dbo].returnDateTime(year(Changes.ChangeWhen),month(Changes.ChangeWhen),day(Changes.ChangeWhen)) between '01/01/2015' And '01/15/2015')
-- In the WHERE statement
DM.FromDateTime Between '01/01/2015' And '01/15/2015'
Or Changes.PreviousDriveDate Between '01/01/2015' and '01/15/2015'
--(dbo.returnDateTime(year(DM.FromDateTime),month(DM.FromDateTime),day(DM.FromDateTime)) Between '01/01/2015' And '01/15/2015')
--Or (dbo.returnDateTime(year(Changes.previousdrivedate),month(Changes.previousdrivedate),day(Changes.previousdrivedate)) Between '01/01/2015' And '01/15/2015')
The query actually ran slower this way.

Query performance to compare date with many join and entity framework

I have this database model :
I use this query :
public List<Film> ListFilmsSortiesDes7DerniersJoursDVD()
{
DateTime dateDans7Jours = DateTime.Now.AddDays(7);
DateTime dateIlYa7Jours = DateTime.Now.AddDays(-7);
return Query(f => f.Releases.Where(r => r.Langue.langue_code == "FR" && r.TypeRelease.typerelease_code == "DVD").FirstOrDefault().release_date > dateIlYa7Jours
&& f.Releases.Where(r => r.Langue.langue_code == "FR" && r.TypeRelease.typerelease_code == "DVD").FirstOrDefault().release_date < dateDans7Jours && !string.IsNullOrEmpty(f.film_image)).ToList();
}
But the SQL generated have bad performance, about 1.3 seconds to return results (with SQL Server Express 2008 and I already have Index on correct fields):
SELECT [Extent1].[film_id] AS [film_id],
[Extent1].[film_image] AS [film_image],
[Extent1].[film_image_thumb] AS [film_image_thumb],
[Extent1].[film_format] AS [film_format],
[Extent1].[film_motsclefs] AS [film_motsclefs],
[Extent1].[film_nom] AS [film_nom],
[Extent1].[film_nomvf] AS [film_nomvf],
[Extent1].[film_synopsis] AS [film_synopsis],
[Extent1].[film_anneeproduction] AS [film_anneeproduction],
[Extent1].[film_budget] AS [film_budget],
[Extent1].[film_dateajout] AS [film_dateajout],
[Extent1].[film_actif] AS [film_actif],
[Extent1].[utilisateur_id] AS [utilisateur_id],
[Extent1].[film_francais] AS [film_francais],
[Extent1].[film_revenue] AS [film_revenue],
[Extent1].[filmgroupe_id] AS [filmgroupe_id]
FROM [dbo].[Film] AS [Extent1]
OUTER APPLY (SELECT TOP (1) [Filter1].[release_date] AS [release_date]
FROM (SELECT [Extent2].[film_id] AS [film_id],
[Extent3].[release_date] AS [release_date],
[Extent3].[typerelease_id] AS [typerelease_id]
FROM [dbo].[FilmRelease] AS [Extent2]
INNER JOIN [dbo].[Release] AS [Extent3]
ON [Extent3].[release_id] = [Extent2].[release_id]
INNER JOIN [dbo].[Langue] AS [Extent4]
ON [Extent3].[langue_id] = [Extent4].[langue_id]
WHERE N'FR' = [Extent4].[langue_code]) AS [Filter1]
INNER JOIN [dbo].[TypeRelease] AS [Extent5]
ON [Filter1].[typerelease_id] = [Extent5].[typerelease_id]
WHERE ([Extent1].[film_id] = [Filter1].[film_id])
AND (N'CINEMA' = [Extent5].[typerelease_code])) AS [Limit1]
CROSS APPLY (SELECT TOP (1) [Filter3].[release_date] AS [release_date]
FROM (SELECT [Extent6].[film_id] AS [film_id],
[Extent7].[release_date] AS [release_date],
[Extent7].[typerelease_id] AS [typerelease_id]
FROM [dbo].[FilmRelease] AS [Extent6]
INNER JOIN [dbo].[Release] AS [Extent7]
ON [Extent7].[release_id] = [Extent6].[release_id]
INNER JOIN [dbo].[Langue] AS [Extent8]
ON [Extent7].[langue_id] = [Extent8].[langue_id]
WHERE N'FR' = [Extent8].[langue_code]) AS [Filter3]
INNER JOIN [dbo].[TypeRelease] AS [Extent9]
ON [Filter3].[typerelease_id] = [Extent9].[typerelease_id]
WHERE ([Extent1].[film_id] = [Filter3].[film_id])
AND (N'CINEMA' = [Extent9].[typerelease_code])) AS [Limit2]
WHERE ([Limit1].[release_date] > '2013-02-04T00:07:48' /* #p__linq__0 */)
AND ([Limit2].[release_date] < '2013-02-18T00:07:48' /* #p__linq__1 */)
AND ([Extent1].[film_image] IS NOT NULL)
Do you please have any ideas to improve performance of this query ?
Ok why search complicated when the answer is simple :
public List<Film> ListFilmsSortiesDes7DerniersJoursCinema()
{
DateTime dateDans7Jours = DateTime.Now.AddDays(7);
DateTime dateIlYa7Jours = DateTime.Now.AddDays(-7);
return Query(f => f.Releases.Where(r => r.Langue.langue_code == "FR" && r.TypeRelease.typerelease_code == "CINEMA" && r.release_date > dateIlYa7Jours && r.release_date < dateDans7Jours).Any()).ToList();
}
I did a join in too

Linq To Entities Generating Big Queries

I've been running a trace on some of the queries Linq is generating and they seem very unoptimized and clumsy.
I realise you dont know my data structure but is tere anything immidiatly wrong with the following linq query
IQueryable<Tasks> tl = db.Tasks
.Include("Catagories")
.Include("Projects")
.Include("TaskStatuses")
.Include("AssignedTo")
.Where
(t => (t.TaskStatuses.TaskStatusId.Equals(currentStatus) | currentStatus == -1) &
(t.Projects.ProjectId.Equals(projectId) | projectId == -1) &
(t.Subject.Contains(SearchText) | t.Description.Contains(SearchText) | SearchText == "" | SearchText == null) &
(t.Projects.Active == true) &
(t.Catagories.Active == true || t.Catagories==null) &
(t.LoggedBy.UserProfile.Companies.CompanyId == CompanyId) &
(assignedToGuid == rnd | t.AssignedTo.UserId.Equals(assignedToGuid))).OrderBy(SortField + " " + SortOrder);
When it runs it generates this SQL query
exec sp_executesql N'SELECT
[Project1].[C1] AS [C1],
[Project1].[TaskId] AS [TaskId],
[Project1].[Subject] AS [Subject],
[Project1].[Description] AS [Description],
[Project1].[EstimateDays] AS [EstimateDays],
[Project1].[EstimateHours] AS [EstimateHours],
[Project1].[DateLogged] AS [DateLogged],
[Project1].[DateModified] AS [DateModified],
[Project1].[AssignedTo] AS [AssignedTo],
[Project1].[C2] AS [C2],
[Project1].[CatagoryId] AS [CatagoryId],
[Project1].[CatagoryName] AS [CatagoryName],
[Project1].[CreatedOn] AS [CreatedOn],
[Project1].[Active] AS [Active],
[Project1].[CreatedBy] AS [CreatedBy],
[Project1].[C3] AS [C3],
[Project1].[ProjectId] AS [ProjectId],
[Project1].[ProjectName] AS [ProjectName],
[Project1].[CreatedOn1] AS [CreatedOn1],
[Project1].[Active1] AS [Active1],
[Project1].[CreatedBy1] AS [CreatedBy1],
[Project1].[TaskStatusId] AS [TaskStatusId],
[Project1].[StatusName] AS [StatusName],
[Project1].[C4] AS [C4],
[Project1].[ApplicationId] AS [ApplicationId],
[Project1].[UserId] AS [UserId],
[Project1].[UserName] AS [UserName],
[Project1].[LoweredUserName] AS [LoweredUserName],
[Project1].[MobileAlias] AS [MobileAlias],
[Project1].[IsAnonymous] AS [IsAnonymous],
[Project1].[LastActivityDate] AS [LastActivityDate],
[Project1].[UserId1] AS [UserId1],
[Project1].[UserId2] AS [UserId2]
FROM ( SELECT
[Filter1].[TaskId] AS [TaskId],
[Filter1].[Subject] AS [Subject],
[Filter1].[Description] AS [Description],
[Filter1].[AssignedTo] AS [AssignedTo],
[Filter1].[EstimateDays] AS [EstimateDays],
[Filter1].[EstimateHours] AS [EstimateHours],
[Filter1].[DateLogged] AS [DateLogged],
[Filter1].[DateModified] AS [DateModified],
[Filter1].[CatagoryId1] AS [CatagoryId],
[Filter1].[CatagoryName] AS [CatagoryName],
[Filter1].[CreatedBy1] AS [CreatedBy],
[Filter1].[CreatedOn1] AS [CreatedOn],
[Filter1].[Active1] AS [Active],
[Filter1].[ProjectId1] AS [ProjectId],
[Filter1].[ProjectName1] AS [ProjectName],
[Filter1].[CreatedOn2] AS [CreatedOn1],
[Filter1].[Active2] AS [Active1],
[Filter1].[CreatedBy2] AS [CreatedBy1],
[Filter1].[TaskStatusId1] AS [TaskStatusId],
[Filter1].[StatusName] AS [StatusName],
[Filter1].[ApplicationId1] AS [ApplicationId],
[Filter1].[UserId1] AS [UserId],
[Filter1].[UserName1] AS [UserName],
[Filter1].[LoweredUserName1] AS [LoweredUserName],
[Filter1].[MobileAlias1] AS [MobileAlias],
[Filter1].[IsAnonymous1] AS [IsAnonymous],
[Filter1].[LastActivityDate1] AS [LastActivityDate],
[Filter1].[UserId2] AS [UserId1],
[Join12].[UserId3] AS [UserId2],
1 AS [C1],
1 AS [C2],
1 AS [C3],
1 AS [C4]
FROM (SELECT [Extent1].[TaskId] AS [TaskId], [Extent1].[Subject] AS [Subject], [Extent1].[Description] AS [Description], [Extent1].[ProjectId] AS [ProjectId2], [Extent1].[TaskStatusId] AS [TaskStatusId2], [Extent1].[LoggedBy] AS [LoggedBy], [Extent1].[AssignedTo] AS [AssignedTo], [Extent1].[EstimateDays] AS [EstimateDays], [Extent1].[EstimateHours] AS [EstimateHours], [Extent1].[DateLogged] AS [DateLogged], [Extent1].[DateModified] AS [DateModified], [Extent1].[CatagoryId] AS [CatagoryId2], [Extent2].[ProjectId] AS [ProjectId3], [Extent2].[ProjectName] AS [ProjectName2], [Extent2].[CreatedOn] AS [CreatedOn3], [Extent2].[CreatedBy] AS [CreatedBy3], [Extent2].[Active] AS [Active3], [Extent3].[CatagoryId] AS [CatagoryId1], [Extent3].[CatagoryName] AS [CatagoryName], [Extent3].[CreatedBy] AS [CreatedBy1], [Extent3].[CreatedOn] AS [CreatedOn1], [Extent3].[Active] AS [Active1], [Join3].[ApplicationId2], [Join3].[UserId4], [Join3].[UserName2], [Join3].[LoweredUserName2], [Join3].[MobileAlias2], [Join3].[IsAnonymous2], [Join3].[LastActivityDate2], [Join3].[UserId5], [Join3].[CompanyId1], [Join3].[Forename1], [Join3].[Surname1], [Join3].[Active4], [Extent6].[UserId] AS [UserId6], [Extent6].[CompanyId] AS [CompanyId2], [Extent6].[Forename] AS [Forename2], [Extent6].[Surname] AS [Surname2], [Extent6].[Active] AS [Active5], [Extent7].[ProjectId] AS [ProjectId1], [Extent7].[ProjectName] AS [ProjectName1], [Extent7].[CreatedOn] AS [CreatedOn2], [Extent7].[CreatedBy] AS [CreatedBy4], [Extent7].[Active] AS [Active2], [Extent8].[ProjectId] AS [ProjectId4], [Extent8].[ProjectName] AS [ProjectName3], [Extent8].[CreatedOn] AS [CreatedOn4], [Extent8].[CreatedBy] AS [CreatedBy2], [Extent8].[Active] AS [Active6], [Extent9].[TaskStatusId] AS [TaskStatusId1], [Extent9].[StatusName] AS [StatusName], [Extent10].[ApplicationId] AS [ApplicationId1], [Extent10].[UserId] AS [UserId1], [Extent10].[UserName] AS [UserName1], [Extent10].[LoweredUserName] AS [LoweredUserName1], [Extent10].[MobileAlias] AS [MobileAlias1], [Extent10].[IsAnonymous] AS [IsAnonymous1], [Extent10].[LastActivityDate] AS [LastActivityDate1], [Join10].[ApplicationId3], [Join10].[UserId7], [Join10].[UserName3], [Join10].[LoweredUserName3], [Join10].[MobileAlias3], [Join10].[IsAnonymous3], [Join10].[LastActivityDate3], [Join10].[ApplicationId4], [Join10].[UserId2], [Join10].[Password], [Join10].[PasswordFormat], [Join10].[PasswordSalt], [Join10].[MobilePIN], [Join10].[Email], [Join10].[LoweredEmail], [Join10].[PasswordQuestion], [Join10].[PasswordAnswer], [Join10].[IsApproved], [Join10].[IsLockedOut], [Join10].[CreateDate], [Join10].[LastLoginDate], [Join10].[LastPasswordChangedDate], [Join10].[LastLockoutDate], [Join10].[FailedPasswordAttemptCount], [Join10].[FailedPasswordAttemptWindowStart], [Join10].[FailedPasswordAnswerAttemptCount], [Join10].[FailedPasswordAnswerAttemptWindowStart], [Join10].[Comment]
FROM [dbo].[Tasks] AS [Extent1]
INNER JOIN [dbo].[Projects] AS [Extent2] ON [Extent1].[ProjectId] = [Extent2].[ProjectId]
LEFT OUTER JOIN [dbo].[Catagories] AS [Extent3] ON [Extent1].[CatagoryId] = [Extent3].[CatagoryId]
LEFT OUTER JOIN (SELECT [Extent4].[ApplicationId] AS [ApplicationId2], [Extent4].[UserId] AS [UserId4], [Extent4].[UserName] AS [UserName2], [Extent4].[LoweredUserName] AS [LoweredUserName2], [Extent4].[MobileAlias] AS [MobileAlias2], [Extent4].[IsAnonymous] AS [IsAnonymous2], [Extent4].[LastActivityDate] AS [LastActivityDate2], [Extent5].[UserId] AS [UserId5], [Extent5].[CompanyId] AS [CompanyId1], [Extent5].[Forename] AS [Forename1], [Extent5].[Surname] AS [Surname1], [Extent5].[Active] AS [Active4]
FROM [dbo].[aspnet_Users] AS [Extent4]
LEFT OUTER JOIN [dbo].[UserProfile] AS [Extent5] ON [Extent4].[UserId] = [Extent5].[UserId] ) AS [Join3] ON [Extent1].[AssignedTo] = [Join3].[UserId4]
INNER JOIN [dbo].[UserProfile] AS [Extent6] ON [Join3].[UserId5] = [Extent6].[UserId]
LEFT OUTER JOIN [dbo].[Projects] AS [Extent7] ON [Extent1].[ProjectId] = [Extent7].[ProjectId]
LEFT OUTER JOIN [dbo].[Projects] AS [Extent8] ON [Extent1].[ProjectId] = [Extent8].[ProjectId]
LEFT OUTER JOIN [dbo].[TaskStatuses] AS [Extent9] ON [Extent1].[TaskStatusId] = [Extent9].[TaskStatusId]
LEFT OUTER JOIN [dbo].[aspnet_Users] AS [Extent10] ON [Extent1].[LoggedBy] = [Extent10].[UserId]
LEFT OUTER JOIN (SELECT [Extent11].[ApplicationId] AS [ApplicationId3], [Extent11].[UserId] AS [UserId7], [Extent11].[UserName] AS [UserName3], [Extent11].[LoweredUserName] AS [LoweredUserName3], [Extent11].[MobileAlias] AS [MobileAlias3], [Extent11].[IsAnonymous] AS [IsAnonymous3], [Extent11].[LastActivityDate] AS [LastActivityDate3], [Extent12].[ApplicationId] AS [ApplicationId4], [Extent12].[UserId] AS [UserId2], [Extent12].[Password] AS [Password], [Extent12].[PasswordFormat] AS [PasswordFormat], [Extent12].[PasswordSalt] AS [PasswordSalt], [Extent12].[MobilePIN] AS [MobilePIN], [Extent12].[Email] AS [Email], [Extent12].[LoweredEmail] AS [LoweredEmail], [Extent12].[PasswordQuestion] AS [PasswordQuestion], [Extent12].[PasswordAnswer] AS [PasswordAnswer], [Extent12].[IsApproved] AS [IsApproved], [Extent12].[IsLockedOut] AS [IsLockedOut], [Extent12].[CreateDate] AS [CreateDate], [Extent12].[LastLoginDate] AS [LastLoginDate], [Extent12].[LastPasswordChangedDate] AS [LastPasswordChangedDate], [Extent12].[LastLockoutDate] AS [LastLockoutDate], [Extent12].[FailedPasswordAttemptCount] AS [FailedPasswordAttemptCount], [Extent12].[FailedPasswordAttemptWindowStart] AS [FailedPasswordAttemptWindowStart], [Extent12].[FailedPasswordAnswerAttemptCount] AS [FailedPasswordAnswerAttemptCount], [Extent12].[FailedPasswordAnswerAttemptWindowStart] AS [FailedPasswordAnswerAttemptWindowStart], [Extent12].[Comment] AS [Comment]
FROM [dbo].[aspnet_Users] AS [Extent11]
LEFT OUTER JOIN [dbo].[aspnet_Membership] AS [Extent12] ON [Extent11].[UserId] = [Extent12].[UserId] ) AS [Join10] ON [Extent1].[LoggedBy] = [Join10].[UserId7]
WHERE (1 = [Extent2].[Active]) AND ((1 = [Extent3].[Active]) OR ([Extent3].[CatagoryId] IS NULL)) ) AS [Filter1]
LEFT OUTER JOIN (SELECT [Extent13].[ApplicationId] AS [ApplicationId], [Extent13].[UserId] AS [UserId8], [Extent13].[UserName] AS [UserName], [Extent13].[LoweredUserName] AS [LoweredUserName], [Extent13].[MobileAlias] AS [MobileAlias], [Extent13].[IsAnonymous] AS [IsAnonymous], [Extent13].[LastActivityDate] AS [LastActivityDate], [Extent14].[UserId] AS [UserId3], [Extent14].[CompanyId] AS [CompanyId], [Extent14].[Forename] AS [Forename], [Extent14].[Surname] AS [Surname], [Extent14].[Active] AS [Active]
FROM [dbo].[aspnet_Users] AS [Extent13]
LEFT OUTER JOIN [dbo].[UserProfile] AS [Extent14] ON [Extent13].[UserId] = [Extent14].[UserId] ) AS [Join12] ON [Filter1].[LoggedBy] = [Join12].[UserId8]
WHERE (([Filter1].[TaskStatusId2] = #p__linq__49) OR (-1 = #p__linq__50)) AND (([Filter1].[ProjectId2] = #p__linq__51) OR (-1 = #p__linq__52)) AND (((CAST(CHARINDEX(#p__linq__53, [Filter1].[Subject]) AS int)) > 0) OR ((CAST(CHARINDEX(#p__linq__54, [Filter1].[Description]) AS int)) > 0) OR (N'''' = #p__linq__55) OR (#p__linq__56 IS NULL)) AND ([Filter1].[CompanyId2] = #p__linq__57) AND ((#p__linq__58 = #p__linq__59) OR ([Filter1].[LoggedBy] = #p__linq__60))
) AS [Project1]
ORDER BY [Project1].[TaskId] ASC',N'#p__linq__49 int,#p__linq__50 int,#p__linq__51 int,#p__linq__52 int,#p__linq__53 nvarchar(4000),#p__linq__54 nvarchar(4000),#p__linq__55 nvarchar(4000),#p__linq__56 nvarchar(4000),#p__linq__57 int,#p__linq__58 uniqueidentifier,#p__linq__59 uniqueidentifier,#p__linq__60 uniqueidentifier',#p__linq__49=1,#p__linq__50=1,#p__linq__51=2,#p__linq__52=2,#p__linq__53=NULL,#p__linq__54=NULL,#p__linq__55=NULL,#p__linq__56=NULL,#p__linq__57=1,#p__linq__58='00000000-0000-0000-0000-000000000000',#p__linq__59='00000000-0000-0000-0000-000000000000',#p__linq__60='00000000-0000-0000-0000-000000000000'
I'm sure there must be a way to get Linq to generate more friendly SQL. If I wrote this same query it could be done in about 5 joins and no inner selects, is it possible to get Linq to tidy this up?
Thanks
Gavin
The large query LINQ to EF creates is just a shortcoming of the first release of the Entity Framework. However, your query contains the phrase .OrderBy(SortField + " " + SortOrder), I believe the preffered way to write this would be .OrderBy(SortField).ThenBy(SortOrder). Also, is there any reason that you are using | instead of || and & instead of && in some places?
IQueryable<Tasks> tl = db.Tasks
.Include("Catagories")
.Include("Projects")
.Include("TaskStatuses")
.Include("AssignedTo")
.Where
(t => (t.TaskStatuses.TaskStatusId.Equals(currentStatus) | currentStatus == -1) &
(t.Projects.ProjectId.Equals(projectId) | projectId == -1) &
(t.Subject.Contains(SearchText) | t.Description.Contains(SearchText) | SearchText == "" | SearchText == null) &
(t.Projects.Active == true) &
(t.Catagories.Active == true || t.Catagories==null) &
(t.LoggedBy.UserProfile.Companies.CompanyId == CompanyId) &
(assignedToGuid == rnd | t.AssignedTo.UserId.Equals(assignedToGuid))).OrderBy(SortField + " " + SortOrder);

Problem in oracle query

Hai guys,
I've a query in which i need to interchange the values of two fields.
The query is as follows:
SELECT TO_DATE(A.G_LEDGER_DATE,'dd/mm/YYY')as G_LEDGER_DATE,C.ACC_MASTER_NAME,
A.G_LEDGER_REF_NO ,
NVL(CASE WHEN B.G_LEDGER_SECTION = 1 THEN
CASE WHEN
(SELECT COUNT(*)FROM SOSTRANS.ACC_GEN_LEDGER WHERE G_LEDGER_SECTION = B.G_LEDGER_SECTION AND G_LEDGER_ID = B.G_LEDGER_ID)> 1 THEN
B.G_LEDGER_VALUE ELSE A.G_LEDGER_VALUE END END,0) AS G_LEDGER_DR_VALUE,
NVL(CASE WHEN B.G_LEDGER_SECTION = -1 THEN
CASE WHEN
(SELECT COUNT(*) FROM SOSTRANS.ACC_GEN_LEDGER WHERE G_LEDGER_SECTION = B.G_LEDGER_SECTION AND G_LEDGER_ID = B.G_LEDGER_ID)> 1 THEN
B.G_LEDGER_VALUE ELSE A.G_LEDGER_VALUE END END,0) AS G_LEDGER_CR_VALUE,
B.G_LEDGER_SECTION,C.ACC_MASTER_ID,SUBSTR(A.G_LEDGER_REF_NO,0,3) AS Types,'Z' as OrderChar ,
CASE WHEN A.G_LEDGER_REMARK IS NULL THEN B.G_LEDGER_REMARK ELSE A.G_LEDGER_REMARK END AS Narration
FROM SOSTRANS.ACC_GEN_LEDGER A
LEFT OUTER JOIN SOSTRANS.ACC_GEN_LEDGER B ON A.G_LEDGER_ID = B.G_LEDGER_ID
LEFT OUTER JOIN SOSMASTER.ACC_ACCOUNT_MASTER C ON A.ACC_MASTER_ID = C.ACC_MASTER_ID WHERE A.G_LEDGER_CANCEL='N' AND
B.ACC_MASTER_ID = 'MSOS000001' AND
A.ACC_MASTER_ID <> 'MSOS000001' AND
A.G_LEDGER_SECTION <> B.G_LEDGER_SECTION AND
A.G_LEDGER_DATE >= '25/sep/2009' AND
A.G_LEDGER_DATE<='26/sep/2009'
ORDER BY OrderChar,G_LEDGER_DATE
Now i get the output as
... G_LEDGER_DR_VALUE G_LEDGER_CR_VALUE .....
... 2000 0 .....
... 3000 0 .....
... -1000 0 .....
I need to get the negetive value of the G_LEDGER_DR_VALUE side in G_LEDGER_CR_VALUE and if negetive value exists in G_LEDGER_CR_VALUE then it should be in the G_LEDGER_DR_VALUE field
Can anyone help me to solve this?
If I understood your question well, you select a value (that I will call g_ledger_value) that you want to appear in a different column depending on its sign.
This is how I would do it :
SELECT
CASE WHEN t.g_ledger_value>0 THEN t.g_ledger_value ELSE 0 END AS g_ledger_dr_value,
CASE WHEN t.g_ledger_value<0 THEN t.g_ledger_value ELSE 0 END AS g_ledger_cr_value
FROM
(SELECT g_ledger_value FROM mytable) t;
It sounds like a combination of SIGN() and CASE is what you need ...
CASE WHEN SIGN(G_LEDGER_DR_VALUE) = -1 then ...
ELSE ...
END
etc
SELECT G_LEDGER_DR_VALUE,
CASE WHEN G_LEDGER_DR_VALUE < 0
THEN G_LEDGER_CR_VALUE
ELSE G_LEDGER_DR_VALUE
END
FROM (...)
Is it that you mean? I suggest calculate values of CR___VALUE and DR_VALUE in subquery, and then in wrapping query make CASE which returns you correct value.

Resources