如何在sql查询中添加Order by

时间:2015-03-22 10:32:35

标签: sql sql-server

update Room set Status = case
                        when Room_Rev.In_DateTime IS NOT NULL and Room_Rev.Out_DateTime IS NULL
                            then 'U'
                        when Room_Rev.In_DateTime IS NOT NULL and Room_Rev.Out_DateTime IS NOT NULL
                            then 'A'     
                        when Room.Status!='R' and Room.Status!='U' and Room.Status!='A'
                            then Room.Status
                         else 'R'
                                end 
                                FROM Room JOIN Room_Rev 
                    ON Room.Room_ID=Room_Rev.Room_ID 
                    and 
                    ((Room_Rev.Start_Date >= '2015-03-22' and Room_Rev.End_Date <= '2015-03-22') 
                                OR 
                    (Room_Rev.Start_Date<= '2015-03-22' and Room_Rev.End_Date> '2015-03-22') 
                                OR 
                    (Room_Rev.Start_Date< '2015-03-22' and Room_Rev.End_Date>= '2015-03-22'))

如何通过Rev_ID desc在查询中添加订单? 有两个表是Room和Room_Rev, 他们是一对多的关系

Room_Rev table 最后两行ROM0006已经填充了In_DateTime和Out_DateTime, 因此它看出来, 并且最后一行插入新的预订, In_DateTime为null 因此我需要查询返回&#39; R&#39; (保留状态)

1 个答案:

答案 0 :(得分:1)

作为可能的解决方案之一,我建议使用嵌套查询而不是UPDATE语句中的连接。更新的逻辑对我来说并不完全清楚,因此我将OP的最终更新保留为正确的排序顺序(注意我在嵌套的SELECT语句中使用了top 1order by room_ID)。但是,这种方法允许处理适用于SELECT的所有常用技术。

update Room set Status = (select TOP 1 case
        when Room_Rev.In_DateTime IS NOT NULL and Room_Rev.Out_DateTime IS NULL
            then 'U'
        when Room_Rev.In_DateTime IS NOT NULL and Room_Rev.Out_DateTime IS NOT NULL
            then 'A'     
        when Room.Status!='R' and Room.Status!='U' and Room.Status!='A'
            then Room.Status
            else 'R'
        end 
    FROM Room_Rev 
    WHERE Room.Room_ID=Room_Rev.Room_ID 
    and 
    ((Room_Rev.Start_Date >= '2015-03-22' and Room_Rev.End_Date <= '2015-03-22') 
                OR 
    (Room_Rev.Start_Date<= '2015-03-22' and Room_Rev.End_Date> '2015-03-22') 
                OR 
    (Room_Rev.Start_Date< '2015-03-22' and Room_Rev.End_Date>= '2015-03-22'))
    ORDER BY Room_Rev.Room_Id
    )

PS。作为一条建议,我仍然认为这种方法是无效的。它会阻止数据的正常标准化。您希望在需要时始终动态查询此信息,而不是将静态值写入ROOM.status