【问题标题】:Challenges with Transforming Postgresql into Redshift (Filter Where)将 Postgresql 转换为 Redshift 的挑战(过滤位置)
【发布时间】:2021-07-14 11:16:26
【问题描述】:

我在从 postgresql 转换为 redshift 方言时注意到一些事情,当使用过滤器 where 时,但不能完全解释为什么这 2 个查询会产生不同的结果。希望有人能解释一下。

Postgresql:

select date_trunc('week', date)::DATE as "Week", 
date_trunc('year', date)::DATE as "Year",
country, 
region, 
count(distinct o.id) filter (where status='delivered') as "Delivered",
count(distinct o.id) filter (where status='packaged') as "Packaged"
from country as c
left join orders as o on c.order_id=o.id and date_trunc('week', o.date)::DATE=date_trunc('week', c.date)::DATE and date_trunc('year', o.date)::DATE=date_trunc('year', c.date)::DATE
where country='IT'
and product='CAT'
group by 1,2
order by 1

通过此查询,我可以查看国家 IT、产品 CAT 在该年和该周交付和包装了多少订单

转换为 Redshift(不能在 where 使用过滤器 - 用 case when 代替)

select extract(week from date) as "Week", 
extract(year from date) as "Year", 
country, 
region, 
case when status='delivered' then count(distinct o.id) as "Delivered",
case when status='packaged' then count(distinct o.id) as "Packaged"
from country as c
left join orders as o on c.order_id=o.id and extract(week from o.date)=extract(week from c.date) and extract(year from o.date)=extract(year from c.date)
where country='IT'
and product='CAT'
group by 1,2, status
order by 1

这里有一些变化:

  1. 要提取的日期截断
  2. 过滤(其中..)以区分大小写
  3. 将状态添加到分组依据(否则会出错)

但主要问题是我没有得到相同的输出,相反,我在同一周有几行,并且值正在跳过行。 (所以它不仅仅是重复的行,我可以通过使用 distinct 轻松摆脱)

【问题讨论】:

    标签: sql filter group-by amazon-redshift aggregate-functions


    【解决方案1】:

    您将case 放在错误的位置。等价的逻辑是:

    select date_trunc('week', date)::DATE as Week, 
           date_trunc('year', date)::DATE as Year,
           country, region, 
           count(distinct case when status = 'delivered' then o.id end) as Delivered,
           count(distinct case when status = 'packaged' then o.id end) as Packaged
    from country c left join
         orders o
         on c.order_id = o.id and
            date_trunc('week', o.date)::DATE = date_trunc('week', c.date)::DATE and
            date_trunc('year', o.date)::DATE = date_trunc('year', c.date)::DATE
    where country = 'IT' and product = 'CAT'
    group by 1, 2
    order by 1;
    

    【讨论】:

      猜你喜欢
      • 2012-04-15
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2017-03-07
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      相关资源
      最近更新 更多