gpt4 book ai didi

PostgreSQL:表过滤——我正在尝试过滤一个表,这样我就可以根据一列的结果保留所有相关结果(包括重复项)

转载 作者:行者123 更新时间:2023-11-29 13:45:13 25 4
gpt4 key购买 nike

我正在尝试编写一个查询来帮助我过滤如下表:

order_number | line_type | price | grand_total
---------------------------------------------
34 | promo | 4.35 | 86.25
34 | tax | 2.50 | 86.25
34 | shipping | 3.40 | 86.25
12 | shipping | 2.50 | 12.00
123 | promo | 8.10 | 34.00
123 | shipping | 4.50 | 34.00
55 | shipping | 2.00 | 12.00
55 | tax | 1.20 | 12.00

目的是保留与具有“promo”line_type 的 order_number 关联的所有结果,但删除没有关联“promo”line_type 的 order_numbers 的所有结果。正确过滤后,上表将删除 order_numbers 12 和 55,同时保留 order_numbers 34 和 123 的每个不同的 line_type,如下所示:

order_number | line_type | price | grand_total
---------------------------------------------
34 | promo | 4.35 | 86.25
34 | tax | 2.50 | 86.25
34 | shipping | 3.40 | 86.25
123 | promo | 8.10 | 34.00
123 | shipping | 4.50 | 34.00

是否有特定的条款可以帮助我解决这个问题?

最佳答案

解析函数在这里派上用场。我们可以计算每组订单中具有促销 line_type 的记录数。然后,仅保留与具有一种或多种促销行类型的订单关联的记录。

SELECT
order_number, line_type, price, grand_total
FROM
(
SELECT *,
COUNT(CASE WHEN line_type = 'promo' THEN 1 END) OVER
(PARTITION BY order_number) cnt
FROM yourTable
) t
WHERE cnt > 0;

关于PostgreSQL:表过滤——我正在尝试过滤一个表,这样我就可以根据一列的结果保留所有相关结果(包括重复项),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49503072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com