如何根据条件多次聚合一条记录

nuypyhwy  于 2022-09-27  发布在  Hive
关注(0)|答案(2)|浏览(172)

我在下表中有一些记录。

  1. product_id produced_date expired_date
  2. 123 2010-02-01 2012-05-31
  3. 234 2013-03-01 2014-08-04
  4. 345 2012-05-01 2018-02-25
  5. ... ... ...

我希望输出显示我们目前每月有多少未过期产品。(例如,如果产品在2004年8月到期,我们仍将其计入8月库存)

  1. Month n_products
  2. 2010-02-01 10
  3. 2010-03-01 12
  4. ...
  5. 2022-07-01 25
  6. 2022-08-01 15

我应该如何在Presto或Hive中做到这一点?非常感谢。

fwzugrvs

fwzugrvs1#

您可以使用下面的SQL。
这里我们使用case when来检查产品是否过期(e1d1e),如果产品已过期,我们将其相加以获得已过期产品的计数。然后对到期月份的数据进行分组。

  1. select
  2. TRUNC(expired_date, 'MM') expired_month,
  3. SUM( case when produced_date >= expired_date then 1 else 0 end) n_products
  4. from mytable
  5. group by 1
jpfvwuh4

jpfvwuh42#

我们可以使用unnest和sequence函数来创建派生表;将我们的表与这个派生表连接起来,应该可以得到所需的结果。

  1. Select m.month,count(product_id) as n_products
  2. (Select
  3. (select x
  4. from unnest(sequence(Min(month(produced_date)), Max(month(expired_date)), Interval '1' month)) t(x)
  5. ) as month
  6. from table) m
  7. left join table t on m.month >= t.produced_date and m.month <= t.expired_date
  8. group by 1
  9. order by 1

相关问题