-1

の難しさは何ORDER BYですか? UNIONここではサポートしていません。

表示中

キーワード '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クエリに対して指定できる句は 1 つだけです。結果セットは 1つしか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 構文を見てください。

Transact 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/1節のあるセクションに注意してくださいORDER BY

ここで、セクション<query_expression>でさらに下に定義されていますUNION

于 2012-09-06T05:27:43.057 に答える