在按顺序使用union子句时出现问题

时间:2019-05-14 09:31:15

标签: sql sql-server

将联合放在两个语句之间时,会发出一些错误。代码如下:

我尝试将方括号放在select语句开始,并按名称顺序结束。但是,对我没有任何作用。有人可以建议这段代码有什么问题吗?

select TOP(1) name from hack
where len(name) in (select max(len(name)) from hack )
order by name

UNION

select TOP(1) name from hack
where len(name) in (select min(len(name)) from hack )
order by name

收到以下错误:

  

关键字“ UNION”附近的语法不正确。

3 个答案:

答案 0 :(得分:1)

不需要where

select h.*
from (select top (1) name
       from hack h
       order by len(name), name asc
     ) h
union all
select h.*
from (select top (1) name
       from hack h
       order by len(name) desc, name
     ) h;

答案 1 :(得分:0)

您需要使用子查询:

select name
from   (
         select TOP(1) name 
         from hack 
         where len(name) in (select max(len(name)) from hack )
         order by name
      ) A

UNION

select name
from   (
         select TOP(1) name 
         from hack 
         where len(name) in (select min(len(name)) from hack )
         order by name
      ) B

答案 2 :(得分:0)

仅访问表一次:

SELECT a.Name
FROM (
    SELECT h.Name
        ,ROW_NUMBER()OVER(ORDER BY LEN(h.Name) DESC, h.Name) AS [rnMax]
        ,ROW_NUMBER()OVER(ORDER BY LEN(h.Name) ASC, h.Name) AS [rnMin]
    FROM hack h
) a
WHERE (a.rnMin = 1 OR a.rnMax = 1)
GROUP BY a.Name
ORDER BY a.Name
;