我在SQL Server中有一个查询。
有一个临时表#final,如下所示
我想只获取具有Maximum EXPECTEDENDDATE的每个项目的单行。
答案 0 :(得分:1)
尝试下面的一个: -
Select f1.*
From #Final As f1 With (Nolock)
Join
(
Select Max(EXPECTEDENDDATE) As EXPECTEDENDDATE
,EmployeeCode
,ProjectCode
From #Final As t With (Nolock)
Group By t.EmployeeCode
,t.ProjectCode
) As f On f1.EmployeeCode = f.EmployeeCode
And f1.ProjectCode = f.ProjectCode
ANd f1.EXPECTEDENDDATE = f.EXPECTEDENDDATE
<强>更新强>
Declare @final Table
(
EmployeeCode Int
,ProjectName Varchar(500)
,ExpectedStartDate Date
,ExpectedEndDate Date
,DaysAllocated Int
)
Declare @SameStartProjects Table
(
EmployeeCode Int
,ProjectName Varchar(500)
,RowNum BigInt
)
Insert Into @final(EmployeeCode,ProjectName,ExpectedStartDate,ExpectedEndDate,DaysAllocated) Values
(1149,'INT-Vibrant Web','2015-04-22','2015-05-21',14)
,(1149,'INT-Vibrant Web','2015-05-22','2015-05-31',6)
,(1149,'Praetorian Track Off','2015-03-19','2015-05-22',15)
,(1149,'Praetorian Track Off','2015-03-19','2015-06-11',20)
,(1149,'RPost Phase ||','2015-05-01','2015-05-31',20)
Insert Into @SameStartProjects(EmployeeCode,ProjectName,RowNum)
Select p.EmployeeCode
,p.ProjectName
,Row_Number() Over(Partition By p.ExpectedStartDate Order By p.ExpectedStartDate) As RowNum
From @final As p
Select s.*
From @final As s
Join
(
Select f.EmployeeCode
,f.ProjectName
,f.ExpectedStartDate
,Max(f.ExpectedEndDate) As ExpectedEndDate
,Max(sp.RowNum) As RowNum
From @final As f
Join @SameStartProjects As sp On f.EmployeeCode = sp.EmployeeCode
And f.ProjectName = sp.ProjectName
Group By f.EmployeeCode
,f.ProjectName
,f.ExpectedStartDate
) As f On s.EmployeeCode = f.EmployeeCode
And s.ProjectName = f.ProjectName
And s.ExpectedEndDate = f.ExpectedEndDate
以上,@ final是你的#final表,我没有采用例如
的所有属性<强>输出: - 强>