很酷的问题...
Snowflake 的好处是我们可以使用蛮力方法……预先计算所有可能的组合,然后使用qualify和row_number过滤重复项并使用ascii。
为了让它更有趣,我包括退货(所以数量可以从 -10 到 10)并添加了第四个产品 @ 135 美元。我确实将不同产品的总数限制为 2 ...但这可以很容易地推到 3。
select
cust_total,
product,
second_product,
quantity,
second_quantity,
ascii(product)+ascii(second_product) basket,
quantity+second_quantity basket_quantity
from
(select
ap1.product,
ap2.product second_product,
ap1.quantity,
ap2.quantity second_quantity,
sum(ap1.revenue_combos) + sum(ap2.revenue_combos) cust_total
from
all_possibles ap1,
all_possibles ap2
where
ap1.product<>ap2.product
group by
1,2,3,4)
group by
1,2,3,4,5,6
qualify
1=
row_number() over
(partition by cust_total,basket,basket_quantity
order by product,second_product)
完整复制|粘贴|在 SQL 中运行:
with all_possibles as (
select
*
from
(
SELECT
seq4() -10 quantity,
quantity * prod_price_1 A,
quantity * prod_price_2 B,
quantity * prod_price_3 C,
quantity * prod_price_4 D
FROM
TABLE (GENERATOR (ROWCOUNT => 21)),
(
select
/*UNIFORM (1, 500, random())*/250::int prod_price_1,
/*UNIFORM (1, 500, random())*/350::int prod_price_2,
/*UNIFORM (1, 500, random())*/500::int prod_price_3,
/*UNIFORM (1, 500, random())*/135::int prod_price_4
)
) unpivot (
revenue_combos for product in (
A,
B,
C,
D
)
)
)
select
cust_total,
product,
second_product,
quantity,
second_quantity,
ascii(product)+ascii(second_product) basket,
quantity+second_quantity basket_quantity
from
(select
ap1.product,
ap2.product second_product,
ap1.quantity,
ap2.quantity second_quantity,
sum(ap1.revenue_combos) + sum(ap2.revenue_combos) cust_total
from
all_possibles ap1,
all_possibles ap2
where
ap1.product<>ap2.product
group by
1,2,3,4)
group by 1,2,3,4,5,6
qualify
1= row_number() over (partition by cust_total,basket,basket_quantity order by product,second_product )