2013-03-22 47 views
1

我想确定哪些表中包含最早的记录。要做到这一点,我想我可能只是说:从UNION子查询中获得排名第一

SELECT TOP 1 TableName FROM 
( 
    SELECT CreateDate, 'Table1' as TableName FROM Table1 
    UNION 
    SELECT CreateDate, 'Table2' as TableName FROM Table2 
) 
ORDER BY CreateDate 

在SQL Server 2008R2它告诉我那里有一个语法错误附近“秩序”。

任何想法?

回答

5

你需要给你的子查询的别名:

SELECT TOP 1 TableName FROM 
( 
    SELECT CreateDate, 'Table1' as TableName FROM Table1 
    UNION 
    SELECT CreateDate, 'Table2' as TableName FROM Table2 
) q 
ORDER BY CreateDate 
1

你没有在子查询定义一个别名,

SELECT TOP 1 TableName 
FROM 
    ( 
     SELECT CreateDate, 'Table1' as TableName FROM Table1 
     UNION 
     SELECT CreateDate, 'Table2' as TableName FROM Table2 
    ) aliasName  -- <<== ADD HERE 
ORDER BY CreateDate 

ALIAS需要为了要识别的子查询。

1
SELECT TOP 1 TableName FROM 
( 
    SELECT CreateDate, 'Table1' as TableName FROM Table1 
    UNION 
    SELECT CreateDate, 'Table2' as TableName FROM Table2 
) RandomName 
ORDER BY CreateDate 
0

所有的人(到目前为止)有正确答案(您需要为您的派生表的别名),但我还建议您不要将所有的CreateDate和TableName值进行UNIONing和排序,而是从每个表中获取最小的CreateDate,并培养在不需要消除重复项时使用UNION ALL的习惯。所以,像这样:

SELECT TOP 1 TableName FROM 
( 
    SELECT MIN(CreateDate) AS CreateDate, 'Table1' as TableName FROM Table1 
    UNION ALL 
    SELECT MIN(CreateDate) AS CreateDate, 'Table2' as TableName FROM Table2 
) x 
ORDER BY CreateDate ASC 
相关问题