且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有联合的情况下修改以下查询?

更新时间:2022-11-03 15:22:39

使用UNION没有任何问题。它可能比使用OR逻辑布尔运算符执行得更快,因为它很可能会有更少的表读取。如果需要,可以尝试获取查询的上半部分,并使用下面的代码替换WHERE子句。我相信它会起作用,但没有任何数据很难说。



 其中(tm.SubmissionStatus =  0   pm.PositionId   in 选择 PositionId 来自 TimesheetMasters))


I want to get rid of the union but still need the same resultset.

I'm new to sql Please help.

[EIDT]Duplicated content has been removed - Maciej Los[/EDIT]

What I have tried:

Query::

select con.FirstName +' ' +con.LastName as ConsultantName,PositionName,MAX(tm.TsId)  as TsId, (pm.PositionId), tm.FromDate,tm.ToDate from TimesheetMasters tm
          left join PositionMasters pm on tm.PositionId=pm.PositionId
          left join Consultants con on con.ConsultantId=pm.ConsultantId

          where  tm.SubmissionStatus=0 
          --and tm.TsId in ( select MAX( TsId) from TimesheetMasters group by PositionId)
          and convert(date, tm.ToDate) between convert(date, DATEADD(day,-30,GETDATE())) and CONVERT(date, GETDATE())
          and pm.CompanyKeyId=@CompanyKeyId
          group by con.FirstName +' ' +con.LastName,PositionName,tm.TsId,pm.PositionId, tm.FromDate,tm.ToDate
          --order by TsId desc


          union

-- Position created but Timesheet is not submitted till now

select con.FirstName +' ' +con.LastName as ConsultantName,PositionName,null as TsId, pm.PositionId,pm.StartDate, pm.EndDate 
          from PositionMasters pm 
          left join Consultants con on con.ConsultantId=pm.ConsultantId
          where pm.PositionId not in (select PositionId from TimesheetMasters) 
          and pm.CompanyKeyId=@CompanyKeyId
          and convert (date,pm.StartDate) between convert(date, DATEADD(day,-30,GETDATE())) and CONVERT(date, GETDATE())

There is nothing wrong with using UNION. It would probably perform faster than using the OR logical boolean operator because it most likely will have less table reads. If you want, you can try and take the top half of the query and substitute the WHERE clause with the code below. I believe it will work, but hard to tell without any data.

where (tm.SubmissionStatus = 0 OR pm.PositionId not in (select PositionId from TimesheetMasters))