Sql 当前日期和过去30天的总值
我目前拥有的代码显示了每天的当前值,并给出了运行总数Sql 当前日期和过去30天的总值,sql,netezza,cumulative-sum,aginity,Sql,Netezza,Cumulative Sum,Aginity,我目前拥有的代码显示了每天的当前值,并给出了运行总数 select t.lgl_entity_nm, d.date_key, count(distinct s.site_key) AS Dis, SUM(Dis) over (partition by t.lgl_entity_nm order by d.date_key ASC rows unbounded preceding) RunningTotal from site_v s join touchpoint_v t on s.site
select t.lgl_entity_nm, d.date_key,
count(distinct s.site_key) AS Dis,
SUM(Dis) over (partition by t.lgl_entity_nm order by d.date_key ASC rows unbounded preceding) RunningTotal
from site_v s
join touchpoint_v t
on s.site_key = t.site_key
join omni_promo_varnt_fact_v o
on o.touchpoint_key = t.touchpoint_key
join date_v d
on d.date_key = o.date_key
where d.date_key between 20190901 and 20190931
and t.lgl_entity_nbr = 1
and tot_selected_qty > 0
and event_typ_cd in ('IS-SPRINT-T', 'IS-PRINT-T')
group by 1,2
给我这个输出:
lgl_entity_nm date_key dis runningtotal
Ahold USA 20190901 729 729
Ahold USA 20190902 733 1462
如果你看一看日期,它是在某个时间段之间设置的。我想要实现的是,它在一行中显示当前日期或任何设置的日期值以及过去30天的总数。假设日期为2019-09-30:
lgl_entity_nm date_key(current date) dis total (past30 days)
Ahold USA 20190930 739 21953
这能实现吗?如果是,怎么做?试试这个
DECLARE @CurrentDate DATE = GETDATE()
,@MonthBack DATE = DATEADD(DAY,-30,GETDATE())
SELECT t.lgl_entity_nm
,@CurrentDate AS CurrentDate
,COUNT(DISTINCT s.site_key) AS Dis
,SUM(Dis) AS RunningTotal
FROM site_v AS s
JOIN touchpoint_v AS t ON s.site_key = t.site_key
JOIN omni_promo_varnt_fact_v AS o ON o.touchpoint_key = t.touchpoint_key
JOIN date_v AS d ON d.date_key = o.date_key
WHERE d.date_key BETWEEN @MonthBack AND @CurrentDate
AND t.lgl_entity_nbr = 1
AND tot_selected_qty > 0
AND event_typ_cd IN ('IS-SPRINT-T', 'IS-PRINT-T')
GROUP BY
t.lgl_entity_nm
我认为您可以从聚合中删除日期键:
select t.lgl_entity_nm, max(d.date_key),
count(distinct s.site_key) as as RunningTotal
from site_v s join
touchpoint_v t
on s.site_key = t.site_key join
omni_promo_varnt_fact_v o join
on o.touchpoint_key = t.touchpoint_key join
date_v d
on d.date_key = o.date_key
where d.date_key between 20190901 and 20190931 and
t.lgl_entity_nbr = 1 and
tot_selected_qty > 0 and
event_typ_cd in ('IS-SPRINT-T', 'IS-PRINT-T')
group by 1;
实际上,这与您的查询有细微的不同,因为您不是计算整个期间的不同site\u key
,而是将每天的不同计数相加。为此:
count(distinct d.date_key || ':' || s.site_key) as RunningTotal
我从你的逻辑中看出了这一点。但是在netezza上工作时,我认为我不能使用@declare选项。可能得想个办法解决它。@darkpunk他的脚本初始化变量。也许可以用在厨房里?或者date_key实际上是一个数字?我不知道Netezza。但是根据需要,应该可以使用类似于
的东西来表示字符(当前日期,'yyyyymmdd')
。或者那应该仍然是CAST
到一个数字。嘿@LukStorms,我会看看我是否可以使用CAST或to_CHAR使其工作。这确实给了我一个运行总数,我想找到一种方法使日期工作,就像当前和最后30天一样。