【问题标题】:Handling nested case statements in Redshift在 Redshift 中处理嵌套的 case 语句
【发布时间】:2020-06-01 09:10:49
【问题描述】:

我正在编写一个需要使用多个 case 语句的 Redshift 查询。

借口: 客户可以与多个组织相关联,例如甜食或盐等。

问: 我们必须首先检查与 'SWEETS' 组织关联的客户是否被选中,如果没有与 'SWEETS' 的隶属关系可用,那么我们必须获取 flag = 1 的组织的 id。

我必须在 redshift 中使用 case 语句来得出结果。

共有三个不同的表,客户表、组织表和确定客户如何与组织关联的 3 个表。

![在此处输入图片描述][1]

我尝试过的代码如下,但执行此代码后,我仍然得到两个组织 ID,而不是一个应该是甜蜜组织的 ID。

SELECT customer_id
     , organization_id
FROM      customer_details  AS customer
LEFT JOIN organization      AS org
       ON customer.customer_id 
      AND organization_id = CASE WHEN organization_id IN (SELECT organization_id
                                                            FROM organization_type
                                                           WHERE organization_type = 'SWEET')
                                 THEN organization_id
                            ELSE org.organization_id END

【问题讨论】:

  • 文本表格的形式提供样本数据和所需结果。
  • case 表达式。另外:这里不需要它。

标签: sql conditional-statements amazon-redshift


【解决方案1】:

你可以使用窗口函数:

select customer_id, organization_id
from (select c.customer_id, o.organization_id,
             row_number() over (partition by o.customer_id order by o.organization_type = 'SWEET' desc) as seqnum
      from customer_details c left join
           organization o 
           on c.customer_id = o.organization_id
     ) co
where seqnum = 1;

【讨论】:

  • 是的,但是如果没有 seqnum =1 的记录,那么理想情况下应该选择第二个组织 ID,其代码为 SALT。
  • @Dushala 。 . . seqnum = 1 总是有记录。如果有一个 SALT 值,那么它就是那个值。否则,它会是别的东西。
  • 太好了,谢谢。我通过引入临时表解决了这个问题。在那个表中,首先所有的糖果记录和他们的相关客户都会被删除。之后我使用 not in ('SWEET') 和 cust not in TEMP 来插入那些客户尚未填充的记录,然后我使用了左边加入以在我的主代码中公开组织 ID。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-12
相关资源
最近更新 更多