1

我想确定哪些表中包含最早的记录。为此,我想我可以说:

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 中,它告诉我“ORDER”附近存在语法错误。

有任何想法吗?

4

4 回答 4

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
于 2013-03-22T18:22:16.060 回答
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为了识别子查询是必需的。

于 2013-03-22T18:22:12.733 回答
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
于 2013-03-22T18:23:37.780 回答
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
于 2013-03-22T18:30:16.167 回答