更新声明集中的order by子句

时间:2013-10-09 08:26:39

标签: sql sql-server tsql

我试图从Update的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

3 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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子句。

答案 2 :(得分: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