1

我试图从更新的 set 语句中的 select 语句中选择前 1 个结果。我可以选择前 1 个,但 order by 子句不起作用。请问有没有办法让它工作或解决方法?

UPDATE  a1
SET     a1.ServiceLength = ( SELECT TOP 1
                                    a3.START_DATE
                                    ORDER BY  a3.START_DATE DESC
                         )
FROM    #t a1
    JOIN #TempService a2 ON a1.EmployeeNo = a2.EMPLOYEE_NO
    JOIN #TempService a3 ON a3.EMPLOYEE_NO = a2.Employee_No
WHERE   a2.START_DATE = a3.END_DATE + 1
    AND @specifiedDate > a2.START_DATE
4

3 回答 3

2

尝试使用 CTE 执行此操作:

WITH TopDate  
AS
(
   SELECT TOP 1 a3.START_DATE, a3.employee_no 
   FROM   #t a1 
   JOIN #tempservice a2 ON a1.employeeno = a2.employee_no 
   JOIN #tempservice a3 ON a3.employee_no = a2.employee_no 
   WHERE  a2.start_date = a3.end_date + 1 
       AND @specifiedDate > a2.start_date
   ORDER BY  a3.START_DATE DESC
)
UPDATE  a1
SET a1.ServiceLength = t.START_DATE
FROM #t a1
INNER JOIN TopDate AS t ON a1.employeeno = t.employee_no 
于 2013-10-09T08:39:30.360 回答
1

您可以使用 MAX(START_DATE) 获取每个员工的最新 START_DATE

update A set A.ServiceLength= (select MAX(B.Start_Date) from #tbl1 B where  B.EmployeeNo=A.EmployeeNo)
from #tbl1 A 

请为您的查询添加必要的 where 子句。

于 2013-10-09T09:02:30.123 回答
0

像这样的东西......:

UPDATE a1 
SET    a1.servicelength = a3.start_date                          
FROM #t a1 
       JOIN #tempservice a2 
         ON a1.employeeno = a2.employee_no 
       JOIN (SELECT *,
             ROW_NUMBER() OVER (PARTITION BY EMPLOYEE_NO ORDER BY START_DATE DESC) AS rnk
             FROM #tempservice) a3 
         ON a3.employee_no = a2.employee_no
         AND a3.rnk = 1      
WHERE  a2.start_date = a3.end_date + 1 
       AND @specifiedDate > a2.start_date 
于 2013-10-09T08:41:36.900 回答