SQL Server 2008合并两个查询的结果

时间:2017-08-04 17:01:27

标签: sql sql-server-2008

我试图在SQL Server 2008中使用UNION运算符合并下面两个查询的结果但是出现以下错误

  

关键字'union'附近的语法不正确。

我的代码:

SELECT TOP 1 
    CITY, LEN(CITY) 
FROM 
    table1 
ORDER BY 
    LEN (CITY), CITY ASC

UNION

SELECT TOP 1 
    CITY, LEN(CITY) 
FROM 
    table1 
ORDER BY 
    LEN (CITY) DESC, CITY ASC

任何意见都将不胜感激。

由于

3 个答案:

答案 0 :(得分:1)

这是正确的方法

Select * From 
(
SELECT TOP 1 
    CITY, cityLen = LEN(CITY) 
FROM 
    table1 
ORDER BY 
    cityLen, CITY ASC
) a
UNION
Select * From 
(
SELECT TOP 1 
    CITY, cityLen = LEN(CITY) 
FROM 
    table1 
ORDER BY 
    cityLen DESC, CITY ASC
) b

或使用Row_Number窗口功能

select * from
(
select *, 
       ROW_NUMBER() OVER(ORDER BY LEN (CITY) DESC, CITY ASC) as Drn,
       ROW_NUMBER() OVER(ORDER BY LEN (CITY) ASC, CITY ASC) as Arn,
FROM table1 
) a
where 1 in (Arn,Drn)

答案 1 :(得分:0)

在第一个select语句中删除ASC order命令。您只能在任何查询结束时对结果进行排序,因为在查询中间排序(如果允许)会导致获得一致结果的许多问题。

编辑:我意识到表格是相同的,您需要使用Union ALL,或者如其他评论中所述,重复项目将在UNION中删除。

SELECT TOP 1 
    CITY, LEN(CITY) 
FROM 
    table1 

UNION ALL

SELECT TOP 1 
    CITY, LEN(CITY) 
FROM 
    table1 
ORDER BY 
    LEN (CITY) DESC, CITY ASC

答案 2 :(得分:0)

在这种情况下,您可以使用Common表表达式。试试这个

;With cte
AS (
select * , ROW_NUMBER() OVER(ORDER BY  LEN (CITY) DESC, CITY ASC) as rn
    FROM table1 
    )
    select * from cte where rn = 1
    union 
    select * from cte where rn = 1