当数据来自许多选择和联合在一起时,是否有可能进行排序?如

Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"

如何按名称对此查询进行排序?

我试过了

Select id,name,age
From Student
Where age < 15 or name like "%a%"
Order by name

但这并不奏效。


当前回答

为什么不用TOP X呢?

SELECT pass1.* FROM 
 (SELECT TOP 2000000 tblA.ID, tblA.CustomerName 
  FROM TABLE_A AS tblA ORDER BY 2) AS pass1
UNION ALL 
SELECT pass2.* FROM 
  (SELECT TOP 2000000 tblB.ID, tblB.CustomerName 
   FROM TABLE_B AS tblB ORDER BY 2) AS pass2

TOP 2000000是一个任意的数字,它大到足以捕获所有的数据。根据您的要求进行调整。

其他回答

要将ORDER BY或LIMIT子句应用于单个SELECT,请将SELECT子句插入圆括号内:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

Select id,name,age
from
(
   Select id,name,age
   From Student
   Where age < 15
  Union
   Select id,name,age
   From Student
   Where Name like "%a%"
) results
order by name

向查询中添加一个列,该列可以对要排序的数据进行子标识。

在下面的例子中,我使用一个公共表表达式,选择您所显示的内容,并将它们放在CTE上的特定组中;然后把这两个组合并成AllStudents。

最后的选择将首先根据SortIndex列对AllStudents进行排序,然后根据名称进行排序,例如:

WITH Juveniles as
(
      Select 1 as [SortIndex], id,name,age From Student
      Where age < 15
),

AStudents as
(
      Select 2 as [SortIndex], id,name,age From Student
      Where Name like "%a%" 
),

AllStudents as
(
      select * from Juveniles
      union 
      select * from AStudents
)

select * from AllStudents
sort by [SortIndex], name;

总而言之,它将获得所有的学生,这些学生将首先按组排序,然后按组内的名字进行子排序。

可以用这个:

Select id,name,age
From Student
Where age < 15
Union ALL
SELECT * FROM (Select id,name,age
From Student
Where Name like "%a%")

如果我希望排序只应用于一个UNION,请使用UNION ALL:

Select id,name,age
From Student
Where age < 15
Union all
Select id,name,age
From 
(
Select id,name,age
From Student
Where Name like "%a%"
Order by name
)