您可以在窗口函数中包含除法吗(红移)
Posted
技术标签:
【中文标题】您可以在窗口函数中包含除法吗(红移)【英文标题】:Can you include a division in a window function (redshift) 【发布时间】:2021-04-24 15:57:28 【问题描述】:我正在查看顾问数据集,并希望使用窗口函数来计算每位顾问的比率。 我想知道顾问在打电话给客户时做了多少销售
select
"consultant", "country",
(count(case when "sales"=1 then "call id" end) / count(case when "call to"='customer' then "call id" end)
over (partition by "consultant" order by "consultant") as "Sales Ratio"
from consultant
group by 1,2
我正在使用的表:
现在我怀疑在这种情况下我是否可以使用窗口函数。我得到的错误是:数据库报告了语法错误:Amazon Invalid operation: syntax error at or near "over" Position: 3191;
【问题讨论】:
你有“then”这个词 .(j)ust 在 over 之前。但你没有条件测试..尝试删除这个词 @scaisEdge 抱歉,在我的情况下你会如何编写窗口函数? 请显示您正在使用的结果。 @GordonLinoff 我不确定你的意思,但由于上面发布的错误,我没有得到结果 【参考方案1】:这两个解析函数需要分别使用OVER
子句,请确保除数大于0或使用适当的条件避免被零除。
select "consultant",
"country",
count(case when "sales"=1 then 1 end) over (partition by "consultant")
/ count(case when "call to"='customer' then 1 end) over (partition by "consultant") as "Sales Ratio"
from consultant
group by 1,2
【讨论】:
好点,我添加了 nullif 来解决这种情况:select "consultant", "country", count(case when "sales"=1 then 1 end) over (partition by "consultant") / (Nullif(count(case when "call to"='customer' then 1 end) over (partition by "consultant")),0) as "Sales Ratio" from consultant group by 1,2
【参考方案2】:
我想知道顾问在打电话给客户时做了多少销售
我有点困惑窗口函数的来源。这听起来像条件聚合:
select "consultant",
sum(case when sales = 1 then 1 else 0 end) as num_sales,
sum(case when sales = 1 and "call to" = 'customer' then 1 else 0 end) as num_sales_with_call,
sum(case when sales = 1 then 1.0 else 0 end) / sum(case when "call to" = 'customer' then 1 end) as sales_to_call_ratio
from consultant
group by 1;
【讨论】:
以上是关于您可以在窗口函数中包含除法吗(红移)的主要内容,如果未能解决你的问题,请参考以下文章