我有一个下面的查询,我运行它为我提供了前一周的单次计数,即Week 44. 截至目前,本周是 45 周。
with data_holder as
(
with tree_post as
(Select contractid as conid, max(goldennmber) as goldennmber
from zeus.user_keys_post group by contractid)
Select * from tree_post join zeus.user_keys_post b
on tree_post.conid = b.contractid and tree_post.goldennmber = b.goldennmber
),
name as
(
SELECT abc, client_id, services from dim.crom c1 where c1.ver = (SELECT MAX(ver) from dim.crom c2
where c1.client_id = c2.client_id)
)
select
count(distinct(clientid))
from data_holder
left join name
on name.client_id = data_holder.clientid
where POC NOT IN ('SGH', 'IKU')
and status IN ('NOTTAKEN')
and (fromWeek <= '44' AND toWeek >= '45')
截至目前,我看到的输出是第 44 周的输出-
Count
-----
124
现在我正在尝试使这个查询动态化,以便它可以让我计算过去 6 周从 44 到 39 不包括当前周的输出,如下所示:
Count Week
------------
124 W44
125 W43
126 W42
127 W41
128 W40
129 W39
因此,如果我每周手动运行它,我每周的情况都会是这样 -
and (fromWeek <= '44' AND toWeek >= '45') // for week 44
and (fromWeek <= '43' AND toWeek >= '44') // for week 43
and (fromWeek <= '42' AND toWeek >= '43') // for week 42
and (fromWeek <= '41' AND toWeek >= '42') // for week 41
and (fromWeek <= '40' AND toWeek >= '41') // for week 40
and (fromWeek <= '39' AND toWeek >= '40') // for week 39
现在我需要以动态的方式每周进行上述手动查询。我想出了下面的查询,但不知何故,当我运行它时我没有得到任何输出。我在下面的查询中做错了什么?
with data_holder as
(
with tree_post as
(Select contractid as conid, max(goldennmber) as goldennmber
from zeus.user_keys_post group by contractid)
Select * from tree_post join zeus.user_keys_post b
on tree_post.conid = b.contractid and tree_post.goldennmber = b.goldennmber
),
name as
(
SELECT abc, client_id, services from dim.crom c1 where c1.ver = (SELECT MAX(ver) from dim.crom c2
where c1.client_id = c2.client_id)
)
select fromWeek,
count(distinct(clientid))
from data_holder
left join name
on name.client_id = data_holder.clientid
where POC NOT IN ('SGH', 'IKU')
and status IN ('NOTTAKEN')
and fromWeek <= date_part(w, current_date - interval '6 weeks')
and toWeek >= date_part(w, current_date)
group by fromWeek
笔记:
fromWeek和toWeek列是整数数据类型,它们包含周数仅供参考。这是一个遗留查询,所以我试图让它动态化。不知道为什么他们在 44 和 45 左右有单引号,但如果我在第 44 周像这样and (fromWeek <= '44' AND toWeek >= '45')或这样运行我的原始手动查询and (fromWeek <= 44 AND toWeek >= 45),我总是得到与 124 相同的数据。