联合和订购(SQL Server)

时间:2017-12-24 06:18:45

标签: sql-server tsql

考虑表格A和表格B,如:

表A:

debit   credit  row
-----------------------
10      0       1
0       10      1
20      0       2
0       20      2
30      0       3
0       30      3

表B:

debit   credit  row
-----------------------
10      0       1
0       10      1
20      0       2
0       20      2
30      0       3
0       30      3

结果:

debit   credit  row
--------------------
10      0       1
20      0       2
30      0       3
0       10      1
0       20      2
0       30      3

我试图联合所有表A,B并先显示借记,然后按行列排序。

1 个答案:

答案 0 :(得分:2)

根据定义,组成UNION的各个SELECT不允许包含ORDER BY子句允许的唯一ORDER BY子句位于UNION的末尾,它适用于整个UNION ,使xxx UNION yyy ORDER BY zzz等效于(xxx UNION yyy)ORDER BY zzz

含义:

无效:

Select debit,credit,row
from
(
   Select debit,credit,row
   From table a
   Where 'condition'
  Union
   Select debit,credit,row
   From table b
   Where 'condition 2'
) results
order by debit, row

有效:

Select debit,credit,row
From table a
Where 'condition'
Union
Select debit,credit,row
From table b
Where 'condition 2'
Order by debit, row