【问题标题】:Return rows if data exists based on a given priority in SQL如果数据存在,则根据 SQL 中的给定优先级返回行
【发布时间】:2015-07-20 13:46:42
【问题描述】:

我正在尝试形成一个 PostgreSQL 语句,该语句根据具有给定优先级的电子邮件类型返回客户电子邮件。下面我有一张桌子,上面有顾客 1 和 2。客户 1 拥有个人和公司电子邮件,而客户 2 拥有公司电子邮件。

我要解决的问题是先返回客户的个人电子邮件,如果它首先存在,如果不返回公司。因此,个人电子邮件优先于公司。这在 PostgreSQL 中是否可行?

 customers
+------------+
| cusomterID |
+------------+
| 1          |
| 2          |
+------------+

customer_email
+------------+-------------+
| cusomterID | email_type  |
+------------+-------------+
| 1          | personal    | -- 0
| 2          | company     | -- 1
| 1          | company     | -- 1
+------------+-------------+

我现在正在尝试的并没有真正起作用。它返回所有行并且不过滤

SELECT *
FROM customers cs
JOIN cumstomer_email cm ON cm.customerId = cs.customreId
WHERE COALESCE(cm.email_type,0) IN (0,1)

【问题讨论】:

    标签: sql postgresql amazon-redshift


    【解决方案1】:

    一种选择是使用条件聚合:

    select customerId, max(case when email_type = 'personal' then email_type
                           else email_type 
                           end) email_type
    from customer_email
    group by customerId
    

    还有一个使用 row_number() 的选项:

    select customerId, email_type
    from (select *, 
               row_number() over (partition by customerId 
                                  order by email_type = 'personal' desc) rn
          from customer_email) t
    where rn = 1
    

    【讨论】:

    • 我会试试这个。谢谢!
    【解决方案2】:

    您可以使用公用表表达式 (CTE) 来做到这一点:

    with emailPriority as (
        select customerId,
               max(email_type) emailType
        from   customer_email
        group by customer_id)
    select  cs.*, cm.email_address
    from    customers cs join emailPriority ep on cs.customerId = ep.customerId
            join customer_email cm on cm.email_type = ep.email_type
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      • 2019-12-01
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      相关资源
      最近更新 更多