【问题标题】:Redshift - Case statement returns duplicatesRedshift - Case 语句返回重复项
【发布时间】:2018-07-04 11:26:07
【问题描述】:

我有一个包含产品名称、订单号和下订单时间的数据集。

prod_name,order_no,order_time
a,101,2018-05-01
a,102,2018-06-04
a,103,2018-05-03
b,104,2018-01-21
b,105,2018-01-11

我正在尝试构建一个报告,显示自第一次订购以来的时间(与当前时间相比),输出如下:

prod_name,time_since_first_sale,aging
a,64,Less than 3 months back
b,177,Less than 6 months back

下面是我正在使用的 SQL:

select DISTINCT b.prod_name,case when((CURRENT_TIMESTAMP - min(a.order_time))) < '90'  THEN 'Less than 3 months'
                               when ((CURRENT_TIMESTAMP - min(order_time))) < '180'  THEN 'Less than 6 months' 
                               else 'Other' end as aging
                               from sales a, prod b where a.id=b.prod_id;

上面的SQL在执行时返回重复,相信它也考虑了sales表中的每个sale_id。我如何修改上述查询以使每个 prod_name 仅获取一条记录。但是,如果我删除 case 语句,则重复项不存在。任何人都可以帮助我做错什么导致这些重复。

我正在使用 Amazon Redshift 数据库。

谢谢..

【问题讨论】:

    标签: sql case amazon-redshift


    【解决方案1】:

    永远不要FROM 子句中使用逗号。 总是使用正确的、明确的、标准的JOIN语法。

    当你打算使用GROUP BY时,不要使用SELECT DISTINCT

    所以你的查询应该是这样的:

    select p.prod_name,
           (case when CURRENT_TIMESTAMP - min(s.order_time) < '90'  
                 then 'Less than 3 months'
                 when CURRENT_TIMESTAMP - min(s.order_time) < '180' then 'Less than 6 months' 
                 else 'Other'
            end) as aging
    from sales s join
         prod p
         on s.id = p.prod_id
    group by p.prod_name;
    

    请注意,我还添加了合理的表别名(表名的缩写)和限定的 all 列引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      相关资源
      最近更新 更多