Tsql 从UNION子查询中获取Top 1

Tsql 从UNION子查询中获取Top 1,tsql,Tsql,我想确定许多表中哪一个包含最早的记录。为此,我想我可以说: SELECT TOP 1 TableName FROM ( SELECT CreateDate, 'Table1' as TableName FROM Table1 UNION SELECT CreateDate, 'Table2' as TableName FROM Table2 ) ORDER BY CreateDate 在SQLServer2008R2中,它告诉我在“ORDER”附近有一个语法错误 有什么想法吗?

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

SELECT TOP 1 TableName FROM
( 
  SELECT CreateDate, 'Table1' as TableName FROM Table1 
  UNION
  SELECT CreateDate, 'Table2' as TableName FROM Table2
)
ORDER BY CreateDate
在SQLServer2008R2中,它告诉我在“ORDER”附近有一个语法错误


有什么想法吗?

您还没有在子查询上定义别名

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

需要别名才能识别子查询。

您尚未在子查询上定义别名

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

需要别名才能识别子查询。

您需要为子查询提供别名:

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

您需要为子查询提供别名:

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

到目前为止,所有其他表都有正确的答案您需要为派生表使用别名,但我还建议您不要对所有CreateDate和TableName值进行联合和排序,而是只从每个表中获取最小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

到目前为止,所有其他表都有正确的答案您需要为派生表使用别名,但我还建议您不要对所有CreateDate和TableName值进行联合和排序,而是只从每个表中获取最小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