带子查询的联合查询违反了子句的顺序

时间:2011-07-12 15:43:49

标签: sql tsql

我有一个问题:

select * from (select top 100 percent ... from [table] 
    where [field1] is not null
    order by [field1]) a 
union all 
select * from (select top 100 percent ... from [table]
    where [field1] is null 
    order by [field2]) b

子查询正确排序结果。我想要第一个子查询的确切结果,然后是第二个子查询的确切结果。但是,我实际上是以一种奇怪的方式排序连续的结果,我甚至无法辨别出一个模式。我有[field2]值分散在结果集上,显然是随机的。

如何在顶部获得第一个查询结果,在底部获得第二个查询结果?

编辑:为了澄清,我希望按照自己的条件排序顶级查询,然后然后我希望底层查询按照自己的条件排序。

2 个答案:

答案 0 :(得分:4)

我不确定,UNION ALL是否意味着保留行的顺序 您可以使用以下语句强制执行所需的订单:

select [field1] from
(
    select * from
    (select 1 as query_number, [field1], [field1] as [order_field] from [table] 
        where [field1] is not null) a 
    union all 
    select * from
    (select 2 as query_number, [field1], [field2] as [order_field] from [table]
        where [field1] is null) b
)
order by query_number, [order_field];

答案 1 :(得分:0)

select * from (select top 100 percent ...,  1 AS q from [table] 
    where [field1] is not null
    order by [field1]) a 
union all

select * from (select top 100 percent ...,  2 AS q from [table]
    where [field1] is null 
    order by [field2]) b

order by q
       , CASE q
           WHEN 1 THEN fieldX   
           WHEN 2 THEN fieldY
         END