从UNION Subquery获得前1名

时间:2013-03-22 18:21:32

标签: tsql

我想确定哪些表包含最早的记录。要做到这一点,我想我可以说:

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 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

所有其他的(到目前为止)都有正确的答案(你需要派生表的别名),但我也建议你不要使用UNIONing并对所有的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