邮政系统 |使用促销代码后获取所有 ID
Postgres | Get all ids after a promo code is used
我正在尝试获取所有使用特定促销代码 (ABC123) 的订单 ID。但是,我想查看所有后续订单,而不仅仅是所有 ID。例如,如果我们有以下 table:
Account_id
order_id
promo_code
1
123
NULL (no promo code used)
2
124
ABC123
3
125
HelloWorld!
2
125
NULL
1
126
ABC123
2
127
HelloWorld!
3
128
ABC123
理想情况下,我想要得到的是这个(按account_id排序):
Account_id
order_id
promo_code
1
126
ABC123
2
124
ABC123
2
125
NULL
2
127
HelloWorld!
3
128
ABC123
如您所见,promo_code = ABC123 就像一个占位符,一旦找到该 ID,我就想要所有前面的 order_ids。
到目前为止,要归档所有使用此 promo_code 的 account_id 是:
SELECT account_ids, order_id, promo_code
FROM orders
WHERE account_id IN (SELECT account_id FROM order WHERE promo_code = 'ABC123');
这使我能够获得使用了所需 promo_code 的订单的 account_id。
提前致谢!
提取所有使用 'ABC123' 的 account_id
-s 和最小的相应 order_number
-s(t
CTE),然后将它们与 table 和 filter/order 结果集。
with t as
(
select distinct on (account_id) account_id, order_id
from the_table where promo_code = 'ABC123'
order by account_id, order_id
)
select the_table.*
from the_table
inner join t on the_table.account_id = t.account_id
where the_table.order_id >= t.order_id -- the subsequent orders
order by the_table.account_id, the_table.order_id;
我正在尝试获取所有使用特定促销代码 (ABC123) 的订单 ID。但是,我想查看所有后续订单,而不仅仅是所有 ID。例如,如果我们有以下 table:
Account_id | order_id | promo_code |
---|---|---|
1 | 123 | NULL (no promo code used) |
2 | 124 | ABC123 |
3 | 125 | HelloWorld! |
2 | 125 | NULL |
1 | 126 | ABC123 |
2 | 127 | HelloWorld! |
3 | 128 | ABC123 |
理想情况下,我想要得到的是这个(按account_id排序):
Account_id | order_id | promo_code |
---|---|---|
1 | 126 | ABC123 |
2 | 124 | ABC123 |
2 | 125 | NULL |
2 | 127 | HelloWorld! |
3 | 128 | ABC123 |
如您所见,promo_code = ABC123 就像一个占位符,一旦找到该 ID,我就想要所有前面的 order_ids。
到目前为止,要归档所有使用此 promo_code 的 account_id 是:
SELECT account_ids, order_id, promo_code
FROM orders
WHERE account_id IN (SELECT account_id FROM order WHERE promo_code = 'ABC123');
这使我能够获得使用了所需 promo_code 的订单的 account_id。
提前致谢!
提取所有使用 'ABC123' 的 account_id
-s 和最小的相应 order_number
-s(t
CTE),然后将它们与 table 和 filter/order 结果集。
with t as
(
select distinct on (account_id) account_id, order_id
from the_table where promo_code = 'ABC123'
order by account_id, order_id
)
select the_table.*
from the_table
inner join t on the_table.account_id = t.account_id
where the_table.order_id >= t.order_id -- the subsequent orders
order by the_table.account_id, the_table.order_id;