-1

有什么困难ORDER BYUNION这里不支持。

显示

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

Select Top2 * from(SELECT * FROM xxx WHERE ID > 0) as X 
                   where ID > z  Order By ID desc
UNION 
 select Top2 * from(SELECT * FROM xxx WHERE ID < 10) as X 
                   where ID < z  Order By ID asc
4

2 回答 2

3

查询只能有一个order by子句。由于union产生了一个结果集,无论如何这不应该是一个问题 - 只需将它放在最后。

Select Top2 * from(SELECT * FROM xxx WHERE ID > 0) as X 
               where ID > z  
UNION 

select Top2 * from(SELECT * FROM xxx WHERE ID < 10) as X 
               where ID < z  

ORDER BY ID asc
于 2012-09-06T05:27:20.907 回答
0

将您的代码更改为

Select  Top 2 
        * 
from    (
            SELECT  * 
            FROM    xxx 
            WHERE ID > 0
        ) as X 
where   ID > z 
UNION   
select  Top 2 
        * 
from    (
            SELECT * 
            FROM xxx 
            WHERE ID < 10
        ) as X 
where   ID < z 
Order By ID asc

查看SELECT (Transact-SQL)并专门查看 TSQL 语法

事务处理 SQL

<SELECT statement> ::=  

    [WITH <common_table_expression> [,...n]]
    <query_expression> 
    [ ORDER BY { order_by_expression | column_position [ ASC | DESC ] } 
  [ ,...n ] ] 
    [ COMPUTE 
  { { AVG | COUNT | MAX | MIN | SUM } (expression )} [ ,...n ] 
  [ BY expression [ ,...n ] ] 
    ] 
    [ <FOR Clause>] 
    [ OPTION ( <query_hint> [ ,...n ] ) ] 

<query_expression> ::= 
    { <query_specification> | ( <query_expression> ) } 
    [  { UNION [ ALL ] | EXCEPT | INTERSECT }
        <query_specification> | ( <query_expression> ) [...n ] ] 

<query_specification> ::= 
SELECT [ ALL | DISTINCT ] 
    [TOP ( expression ) [PERCENT] [ WITH TIES ] ] 

    < select_list > 
    [ INTO new_table ] 
    [ FROM { <table_source> } [ ,...n ] ] 
    [ WHERE <search_condition> ] 
    [ <GROUP BY> ] 
    [ HAVING < search_condition > ] 

请注意<query_expression>带有 0/1ORDER BY子句的部分。

其中,在<query_expression>下面的UNION部分中进一步定义。

于 2012-09-06T05:27:43.057 回答