一定数量的记录的多个LISTAGG行

时间:2017-11-27 02:14:09

标签: oracle11g listagg

我无法解决这个难题。我想按订单的每个第3个跟踪号拆分listagg查询。

Order Tracking
1     123
1     432
1     566 
1     867
1     999 
2     321
2     742
2     456
2     987

我目前的输出是将每个订单的所有跟踪号码混为一起

Order Tracking
1     123, 432, 566, 867, 999
2     321, 742, 456, 987

我想要的结果最多每行3个。

Order Tracking
1     123, 432, 566
1     867, 999
2     321, 742, 456
2     987 

1 个答案:

答案 0 :(得分:0)

您可以在CTE中使用ROW_NUMBER在订单上强加三个分组:

WITH cte AS (
    SELECT "Order", Tracking,
        (ROW_NUMBER() OVER (PARTITION BY "Order" ORDER BY Tracking) - 1) / 3 AS grp
    FROM yourTable
)

SELECT
    "Order",
    LISTAGG(Tracking, ', ') WITHIN GROUP (ORDER BY Tracking) "Tracking"
FROM cte
GROUP BY
    "Order", grp
ORDER BY
    "Order", grp;