【问题标题】:Redshift : Fetch value from table 1 if value exists else pull from table 2Redshift:如果值存在,则从表 1 中获取值,否则从表 2 中提取
【发布时间】:2019-07-15 08:11:52
【问题描述】:

我正在使用 Redshift DB。

我有一个存储在表customers 中的客户 ID 列表

Query : select name from customers

根据购买数据,我有一张包含客户年龄的表格。表名:sales

Query : select name, age_group from sales

我有另一个表,其中包含所有客户的 age_group,无论他们是否存在于 sales 表中。这个表叫customer_profile

Query : select name, age_group from customer_profile

我正在尝试构建一个查询,以便为customers 中的每个客户创建一个标记为age_group 的列。

条件 : 如果age_group 值存在于sales 中,则需要从sales 中提取,否则需要从customer_profile 表中获取数据

【问题讨论】:

    标签: sql amazon-redshift


    【解决方案1】:

    这个怎么样

    SELECT
      t1.name,
      isnull(t1.cp_age, t1.s_age) as age_Group
    FROM
      (
        SELECT
          c.name,
          c.age_group,
          cp.age_group as cp_age,
          s.age_group as s_age
        FROM
          customers c
          LEFT JOIN customer_profile cp on cp.age_group = c.age_group
          and c.name = cp.name
          LEFT JOIN sales s on s.age_group = c.age_group
          and c.name = s.name
      ) as t1
    

    【讨论】:

    • @scottmartin 。 . .您的问题在customers 中没有提到名为age_group 的列。接受这个答案令人困惑。
    • @GordonLinoff,刚刚使用了提到的方法。没有查看实际使用的列。因为这有助于接受答案
    【解决方案2】:

    你可以使用联合

    select name, age_group from sales 
    where age_group is not null or age_group<>0 
    union 
    select name, age_group from customer_profile
    where age_group is not null or age_group<>0
    

    【讨论】:

    • 如果两个表中都存在相同的名称,则不会联合给出重复项
    • @scottmartin no union 将返回不同的名称,它将删除重复的 union all make duplicate
    【解决方案3】:

    假设您在 salescustomer_profile 中没有重复项,我建议:

    SELECT c.*,
           COALESCE(s.age_group, cp.age_group) as age
    FROM customers c LEFT JOIN
         sales s
         ON s.name = c.name LEFT JOIN
         customer_profile cp 
         ON cp.name = c.name AND
            s.name IS NULL;  -- no match in sales
    

    假设您没有重复项,这似乎是最简单的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多