在Oracle中限制LISTAGG结果

时间:2017-05-30 13:56:38

标签: sql oracle listagg

我试图限制我的SQL查询中的一个列,它使用LISTAGG仅将前3行分组到一个列中。

例如:

Table
-----
Name   Orders
---------------
Joe    Joe_Order1
Joe    Joe_Order2
Joe    Joe_Order3
Joe    Joe_Order4
Joe    Joe_Order5
Joe    Joe_Order6
Mark   Mark_Order1
Mark   Mark_Order2
Mark   Mark_Order3
Mark   Mark_Order4

让它返回以下内容......

Name   Recent_Orders
-----------------------------
Joe    Joe_Order1, Joe_Order2, Joe_Order3
Mark   Mark_Order1, Mark_Order2, Mark_Order3

我能够使用listagg连接数据但是,我并不完全确定如何将结果限制为前3条记录。

SELECT NAME, LISTAGG(Orders, ', ') within group(order by Orders)
  as Recent_Orders
FROM
  Order_table
GROUP BY
  NAME

LISTAGG可以吗?任何帮助将不胜感激。感谢

2 个答案:

答案 0 :(得分:1)

您可以通过枚举行并使用case

来完成此操作
SELECT NAME,
       LISTAGG(CASE WHEN seqnum <= 3 THEN Orders END, ', ') WITHIN GROUP (ORDER BY Orders) as Recent_Orders
FROM (SELECT o.*, ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY ?? DESC) as seqnum
      FROM Order_table o
     ) o
GROUP BY NAME;

默认情况下,LISTAGG()会忽略NULL个值,因此您可以按照自己的意愿行事。

??是用于指定排序的列。 SQL表代表无序集;除非列指定了排序,否则没有“前三个”或“后三个”。

答案 1 :(得分:1)

在CTE中应用row_number,然后在WHERE子句中应用限制

with CTE as
(
select row_number() over(partition by NAME order by Orders) as rn,
       a1.*
from Order_Table a1
)
SELECT NAME, LISTAGG(Orders, ', ') within group(order by Orders)
  as Recent_Orders
FROM
  CTE
WHERE 
  rn <=3
GROUP BY
  NAME