Redshift:如果值存在,则从表1中获取值,否则从表2中获取

时间:2019-07-15 08:11:52

标签: sql amazon-redshift

我正在使用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中提取,否则需要从{{1}中获取数据}表

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用工会

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

答案 2 :(得分:0)

假设您在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

如果您没有重复的话,这似乎是最简单的解决方案。