如何在 SQL 子查询中使用 order by?
我有一个名为 ConcatList 的聚合函数,它将值列表连接成单个逗号分隔值。
这是我正在尝试做的一个例子。我有两个表:员工和工作。 Job 是 Employee 的“孩子”。我需要获取员工列表,其中包括与员工相关的以逗号分隔的工作列表,并按工作名称排序。
我以为我可以这样做:
select em.EmployeeId,
em.EmployeeName,
(select ConcatList(jo.JobName)
from Job jo
where jo.EmployeeId = em.EmployeeId
order by jo.JobName)
from Employee em;
但是,这会在“order by”子句上返回以下错误:
ORA-00907: missing right parenthesis
如果我去掉“order by”子句,此 SQL 可以工作,但我需要对作业列表进行排序。
我怎样才能做到这一点?
I have an aggregate function called ConcatList that concatenates a list of values into a single comma separated value.
Here is an example of what I am trying to do. I have two tables: Employee and Job. Job is a "child" of Employee. I need to get a list of the employees that includes a comma-delimited list of the jobs related to the employee, sorted by the name of the job.
I thought I could do this:
select em.EmployeeId,
em.EmployeeName,
(select ConcatList(jo.JobName)
from Job jo
where jo.EmployeeId = em.EmployeeId
order by jo.JobName)
from Employee em;
However, this returns me the following error on the "order by" clause:
ORA-00907: missing right parenthesis
If I get rid of the "order by" clause, this SQL works, but I need to sort the list of jobs.
How can I make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以对连接的记录进行排序,然后聚合结果:
You can sort the joined records and then aggregate the result:
由于
ConcatList
是用户定义的聚合函数,因此修改ConcatList
以对结果进行排序或创建ConcatSortedList
似乎是有意义的对它聚合的数据进行排序的聚合函数。 Gary Myers 有一个用户定义聚合函数的示例,生成一个排序列表。您还可以在 Tim Hall 的网站上了解各种字符串聚合技术。如果必须生成排序列表,那么使用其中许多技术比尝试保证非排序用户定义聚合函数生成排序结果更容易。例如,采用 REF CURSOR 的通用函数相对而言是当需要排序时很容易使用,因为您只需向光标添加
ORDER BY
即可。Since
ConcatList
is a user-defined aggregate function, it would seem to makes sense either to modifyConcatList
to order the results or to create aConcatSortedList
aggregate function that sorts the data it aggregates. Gary Myers has an example of a user-defined aggregate function that produces a sorted list.You can also go through the various string aggregation techniques on Tim Hall's site. If you have to produce a sorted list, using many of those techniques would be easier than trying to guarantee that a non-sorting user-defined aggregate function produces a sorted result. The generic function taking a REF CURSOR, for example, is relatively easy to use when sorting is required because you can just add an
ORDER BY
to the cursor.我从中意识到 wm_concat 是一个分析的示例 --> http://www.tek-tips.com/viewthread.cfm?qid=1629662
Text2 = 随机文本
val = 分组
Example from which I realized wm_concat is an analytic --> http://www.tek-tips.com/viewthread.cfm?qid=1629662
Text2 = random text
val = grouping