【问题标题】:Removing duplicates based on one value根据一个值删除重复项
【发布时间】:2018-10-17 06:09:19
【问题描述】:
    customer id name    Pay_type
    1111    aaaa    regular
    1111    aaaa    late
    1111    aaaa    regular
    1111    aaaa    regular
    2222    bbbb    regular
    2222    bbbb    regular
    2222    bbbb    regular
    3333    cccc    regular
    3333    cccc    late
    4444    dddd    regular
    4444    dddd    regular

我有一个 SQL 查询,它给出了上述结果,我希望该结果删除任何有滞纳金的客户

输出需要是:

customer id name    Pay_type
2222    bbbb    regular
2222    bbbb    regular
2222    bbbb    regular
4444    dddd    regular
4444    dddd    regular

select 
distinct a.customer_id, 
a.name, 
pay_type 
from table a 
left join table b on a.customer_id= b.id 
left join table c on c.id = b.pay_id 
where b.status = 'Done

【问题讨论】:

  • 您能否在您的问题中也包含您的查询?看起来这是 distinct 操作应该能够解决的问题。
  • 请编辑您的问题并在其中包含查询。

标签: postgresql duplicates postgresql-9.4


【解决方案1】:

我会这样做作为反加入:

select *
from table a
where not exists (
  select null
  from table b
  where
    a.customer_id = b.customer_id and
    b.pay_type = 'late'
)

与独特或“不在”方法相比,这具有优势,因为它会在找到匹配项后停止查找。这应该对大型和小型数据集都有效。

任何使用 distinct 的解决方案都必须评估整个数据集,然后删除重复项。

【讨论】:

    【解决方案2】:

    我不确定您的表格到底是什么样子,但您可以执行以下操作:

    WHERE customer_id NOT IN (
        SELECT customer_id
        FROM table_with_customer_and_pay_type
        WHERE pay_type = 'late'
        GROUP BY customer_id )
    

    【讨论】:

      【解决方案3】:

      常用表表达式变体:

      WITH orig_result_set AS (
          select 
          distinct a.customer_id, 
          a.name, 
          pay_type 
          from table a 
          left join table b on a.customer_id= b.id 
          left join table c on c.id = b.pay_id 
          where b.status = 'Done'
      ),
      
      exclude_late_payments AS (
          SELECT DISTINCT customer_id
          FROM orig_result_set
          WHERE pay_type = 'late'
      ),
      
      on_time_payments AS (
          SELECT customer_id,
                 name,
                 pay_type
          FROM orig_result_set
          WHERE customer_id NOT IN exclude_late_payments
      )
      
      SELECT *
      FROM on_time_payments
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-02
        相关资源
        最近更新 更多