【问题标题】:Is there a way to check multiple columns using "IN" condition in Redshift Spectrum?有没有办法在 Redshift Spectrum 中使用“IN”条件检查多个列?
【发布时间】:2020-04-02 12:15:18
【问题描述】:

我有一个名为 customer_details_table 的 Redshift Spectrum 表,其中 id 列不是唯一的。我还有另一列hierarchy,它基于如果它们具有相同的ID,则应该优先考虑哪个记录。这是一个例子:

这里,如果我们多次遇到与28846相同的id,我们会选择John作为合格的,考虑到他的等级最高。

我正在尝试使用id 上的group by 创建此eligibility 列,然后选择对应于最大值hierarchy 的记录。这是我的 SQL 代码:

SELECT *,
CASE WHEN (
     (id , hierarchy) IN 
            (SELECT id , max(hierarchy)
            FROM
              customer_details_table
            GROUP BY id
            )
) THEN 'Qualified' ELSE 'Disqualified' END as eligibility
FROM
  customer_details_table

运行时出现以下错误:

SQL Error [500310] [XX000]: [Amazon](500310) Invalid operation: This type of IN/NOT IN query is not supported yet;

当我的表 (customer_details_table) 是常规 Redshift 表时,上面的代码可以正常工作,但当同一个表是外部光谱表时,它会失败。谁能提出一个好的解决方案/替代方案来在频谱表中实现相同的逻辑?

【问题讨论】:

    标签: sql amazon-redshift greatest-n-per-group window-functions amazon-redshift-spectrum


    【解决方案1】:

    您可以使用窗口函数来生成eligibility 列:

    基本上,您需要按id 对行进行分区,并按每个组内的hierarchy 降序排列。

    select
        *,
        case when row_number() over(partition by id order by hierarchy desc) = 1
            then 'Qualified' else 'Disqualified'
        end eligibility
    from customer_details_table
    

    【讨论】:

      【解决方案2】:

      你可以使用窗口函数:

      select cdt.*
      from (select cdt.*,
                   row_number() over (partition by id order by hierarchy desc) as seqnum
            from customer_details_table cdt
           ) cdt
      where seqnum = 1;
      

      【讨论】:

        猜你喜欢
        • 2015-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-10
        • 2019-10-31
        • 1970-01-01
        • 2011-04-21
        相关资源
        最近更新 更多