Sql 按月计算日期持续时间组
我有一张类似的表格,如下所示:Sql 按月计算日期持续时间组,sql,amazon-redshift,Sql,Amazon Redshift,我有一张类似的表格,如下所示: store manager open close 1 tim 01-Feb-21 *null* 2 anna 01-Feb-21 28-Feb-21 3 ben 01-Feb-21 *null* 4 tim 01-Mar-21 15-Apr-21 我的目标是获得如下所示
store manager open close
1 tim 01-Feb-21 *null*
2 anna 01-Feb-21 28-Feb-21
3 ben 01-Feb-21 *null*
4 tim 01-Mar-21 15-Apr-21
我的目标是获得如下所示的期望输出。如果关闭列为空,则持续时间将继续累计到当前月份。我们的想法是每个经理每月有一行,以及他们管理的所有门店的营业时间总和
month manager duration (days)
Feb-21 tim 28
Mar-21 tim 58
Apr-21 tim 130
Feb-21 anna 28
Mar-21 anna 0
Apr-21 anna 0
Feb-21 ben 28
Mar-21 ben 58
Apr-21 ben 79
我尝试了不同的方法,其中一种是下面的代码,但它仍然不起作用,只花了商店开业当月的时间
WITH duration_calculation
AS (
SELECT t.manager,
t.open,
t.close,
COALESCE(DATEDIFF(day, t.open, t.close), DATEDIFF(day, t.open, CURRENT_DATE)) AS duration
FROM t
)
SELECT DATE_TRUNC('month', t.open) :: date AS month,
d.manager,
SUM(d.duration)
FROM duration_calculation AS d
GROUP BY 1,2
我仍然无法想出解决这个问题的方法,因此如果有人能给我一个如何解决这个问题的建议,我将不胜感激