我当前拥有的代码向我显示了每天的当前值并给出了运行总计。
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
这可以实现吗?如果可以,怎么办?
答案 0 :(得分:0)
尝试一下?
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
答案 1 :(得分:0)
我认为您可以从聚合中删除日期键:
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_key
,而是每天将不同的计数加起来。为此:
count(distinct d.date_key || ':' || s.site_key) as RunningTotal