我们有一个表,其中每个订单的 PromoCodes 作为 JSON 数组,如下
订单_id | promo_json_array |
---|---|
111 | [{PromoCode:"bbb", 折扣: -1 }, {PromoCode:"aaa", Type:FreeShip}] |
222 | [{促销代码:“ccc”,折扣:-2}] |
333 | [{促销代码:"ccc", 折扣:-2}, {促销代码:"aaa"}, {促销代码:"eee"} ] |
444 |
对于每个订单,我需要获取以逗号分隔的促销代码列表(如果有)。
我正在使用 Flatten 来实现此目的,如下所示:
with orders as (
select 111 as order_id, '[{PromoCode:"bbb", Discount: -1 }, {PromoCode:"aaa", Type:FreeShip}]' as promo_json_array
union all
select 222, '[{PromoCode:"ccc", Discount: -2}]'
union all
select 333, '[{PromoCode:"ccc", Discount: -2}, {PromoCode:"aaa"}, {PromoCode:"eee"} ]'
union all
select 444, null
)
--select * from orders;
select order_id, listagg (f.value:PromoCode, ', ')
from orders
, lateral flatten(input => parse_json(orders.promo_json_array)::variant, OUTER => TRUE) as f
group by all
订单_id | 促销代码_已应用 |
---|---|
222 | ccc |
333 | ccc、aaa、eee |
111 | bb、aaa |
444 | |
444 |
然而,这对于大量订单来说非常慢,特别是当我们在 JSON 数组中有很多元素+键值时。有没有更优化的方法来实现这一点?