PostgreSQL: Table 过滤-我正在尝试过滤 table 以便我可以根据一列的结果保留所有相关结果(包括重复项)

PostgreSQL: Table filtering-I am trying to filter a table so I can keep all relevant results (including duplicates) based on the result of one column

我正在尝试编写一个查询来帮助我过滤 table,如下所示:

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 关联的所有结果,但删除没有关联 order_number 的所有结果=20=] line_type。适当过滤后,上面的 table 将删除 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;