简体   繁体   English

在Oracle中限制LISTAGG结果

[英]Limit LISTAGG results in Oracle

I'm trying to limit one of my columns in my SQL query that uses LISTAGG to only group the first 3 rows into a single column. 我试图在使用LISTAGG的SQL查询中限制我的一列,以仅将前3行分组为一个列。

For instance: 例如:

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

Have it return the following... 让它返回以下内容...

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

I'm able to concatenate the data using listagg however, I'm not entirely sure how to limit the results to the first 3 records. 我可以使用listagg连接数据,但是我不确定如何将结果限制为前3个记录。

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

Is this possible with LISTAGG? LISTAGG有可能吗? Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks 谢谢

Apply a row_number in a CTE, then apply the restriction in the WHERE clause 在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

You can do this by enumerating the rows and using case : 您可以通过列举行并使用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;

By default, LISTAGG() ignores NULL values, so this does what you want. 默认情况下, LISTAGG()忽略NULL值,因此您可以执行所需的操作。

The ?? ?? is the column for specifying the ordering. 是用于指定顺序的列。 SQL tables represent unordered sets; SQL表表示无序集; there is no "first three" or "last three" unless a column specifies the ordering. 除非有列指定顺序,否则没有“前三个”或“后三个”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM