当数据来自许多选择和联合在一起时,是否有可能进行排序?如
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
但这并不奏效。
为了使排序只适用于UNION中的第一个语句,你可以把它放在一个带有UNION ALL的子选择中(这两个在Oracle中都是必要的):
Select id,name,age FROM
(
Select id,name,age
From Student
Where age < 15
Order by name
)
UNION ALL
Select id,name,age
From Student
Where Name like "%a%"
或者(针对Nicholas Carey的评论)你可以保证顶部的SELECT是有序的,结果显示在下面的SELECT上面,就像这样:
Select id,name,age, 1 as rowOrder
From Student
Where age < 15
UNION
Select id,name,age, 2 as rowOrder
From Student
Where Name like "%a%"
Order by rowOrder, name
为了添加到旧的主题,我使用了ROW_NUMBER(使用MS SQL)。这允许在union内排序(顺序)。
所以使用来自@BATabNabber的想法来分离联盟的每一半,而@Wodin将整个事情包装在一个选择中,我得到:
Select Id, Name, Age from
(
Select Id, Name, Age, 1 as Mainsort
, ROW_NUMBER() over (order by age) as RowNumber
From Student
Where Age < 15
Union
Select Id, Name, Age, 2 as Mainsort
, ROW_NUMBER() over (Order by Name) as RowNumber
From Student
Where Name like '%a%'
) as x
Order by Mainsort, RowNumber
所以调整,或省略,你想要的顺序,并添加下降,因为你认为合适。
为了使排序只适用于UNION中的第一个语句,你可以把它放在一个带有UNION ALL的子选择中(这两个在Oracle中都是必要的):
Select id,name,age FROM
(
Select id,name,age
From Student
Where age < 15
Order by name
)
UNION ALL
Select id,name,age
From Student
Where Name like "%a%"
或者(针对Nicholas Carey的评论)你可以保证顶部的SELECT是有序的,结果显示在下面的SELECT上面,就像这样:
Select id,name,age, 1 as rowOrder
From Student
Where age < 15
UNION
Select id,name,age, 2 as rowOrder
From Student
Where Name like "%a%"
Order by rowOrder, 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;
总而言之,它将获得所有的学生,这些学生将首先按组排序,然后按组内的名字进行子排序。