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
答案 0 :(得分: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
答案 1 :(得分: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
部分定义了{{1}}。