如何从两个表的并集中选择最大日期?

时间:2012-10-17 22:04:58

标签: tsql

SELECT TOP 1 * FROM 
(
    select max(updatedtimestamp) from db1.dbo.policyrepresentationcache with(nolock)
    UNION
    select max(updatedtimestamp) from db2.dbo.policyrepresentationcache with(nolock)
    ) 
ORDER BY updatedtimestamp

我在这里遇到语法错误,我不知道如何设置它。

2 个答案:

答案 0 :(得分:3)

你刚刚错过了工会生成的表的别名。我把它别名为 a

SELECT TOP 1 a.updatedtimestamp FROM
(
     select max(updatedtimestamp) as updatedtimestamp  
     from db1.dbo.policyrepresentationcache with(nolock)
     UNION
     select max(updatedtimestamp) 
     from db2.dbo.policyrepresentationcache with(nolock)
) a
ORDER BY a.updatedtimestamp

答案 1 :(得分:0)

SELECT TOP 1 Temp.* FROM 
(
    select max(updatedtimestamp) from db1.dbo.policyrepresentationcache with(nolock)
    UNION
    select max(updatedtimestamp) from db2.dbo.policyrepresentationcache with(nolock)
    ) AS Temp
ORDER BY Temp.updatedtimestamp