在SQL中获取两个值中的较大值

时间:2013-03-26 23:44:41

标签: sql-server

我有一个SQL Server表。该表有两个表:Order和OrderInProgress。这两个表具有相似的结构:

Order[InProgress]
-----------------
ID (uniqueidentifier)
CreateDate
...

我需要获得最新的Order或OrderInProgress

DECLARE @latestOrderID uniqueidentifier
@latestOrderID = ?

如何将@latestOrderID设置为最近的Order或OrderInProgress ID?我无法弄清楚如何在SQL中执行此操作。

谢谢!

3 个答案:

答案 0 :(得分:1)

尝试这一点,无论什么时候都应该更有效率。

   select top 1 ID from (
        select top 1 ID from Order order by ID desc
      union all
        select top 1 ID from OrderInProgress order by ID desc
    ) T
    order by ID desc

答案 1 :(得分:0)

你试过了吗?

SELECT TOP 1 @latestOrderID = ID FROM [Order] ORDER BY CreateDate DESC

答案 2 :(得分:0)

SELECT * FROM
(SELECT 'Order' tablename, max(ID) max_id FROM Order
UNION
SELECT 'OrderInProgress' tablename, max(ID) max_id FROM OrderInProgress
) maxes ORDER BY max_id DESC