AccountHmy|UserHmy|Closing|Reason| |TimeStamp
606 |299 |0 |Re-opened for Testing |2015-08-11 10:22:36
606 |108 |1 |Testing Completed |2015-08-10 10:22:36
606 |108 |1 |Re-opened for Testing |2015-08-10 10:15:36
我有一个SQL查询,结果我有4行,
select * from Synergy.dbo.cu_Close_Account_Log SCAL
where SCAL.AccountHmy='602634' order by SCAL.Timestamp desc
现在我需要通过加入上一个表来更新另一个表,我应该只考虑在早期结果集中重新调整的第一个值。
UPDATE
ST
SET
StatusHmy = (
CASE
WHEN ST.StatusHmy = 4 AND SCAL.Closing = 0 THEN 5
WHEN ST.StatusHmy = 4 AND SCAL.Closing = 1 THEN 2
END
)
FROM
Synergy.dbo.cu_Transition ST
LEFT JOIN Synergy.dbo.cu_Close_Account_Log SCAL ON SCAL.AccountHmy = ST.AccountHmy
WHERE
ST.StatusHmy = 4 AND SCAL.Closing IN ( 0,1 )
ORDER BY
SCAL.Timestamp desc
但是,Order By正在抛出一个错误。怎么解决这个问题?
答案 0 :(得分:1)
如果您只想将子查询用于一个值,请使用TOP
和ORDER BY
。这可以在子查询中进行:
UPDATE ST
SET StatusHmy = (CASE WHEN ST.StatusHmy = 4 AND SCAL.Closing = 0 THEN 5
WHEN ST.StatusHmy = 4 AND SCAL.Closing = 1 THEN 2
END )
FROM Synergy.dbo.cu_Transition ST JOIN
(select top 1 scal.*
from Synergy.dbo.cu_Close_Account_Log SCAL
where SCAL.AccountHmy = '602634'
order by SCAL.Timestamp desc
) scal
ON SCAL.AccountHmy = ST.AccountHmy
WHERE ST.StatusHmy = 4 AND SCAL.Closing IN ( 0,1 );