对于上述数据,我想基于对行进行分组来计算每个购买行(购买= 1)的百分比值。
计算条件为:
例如,百分比值应按以下方式计算:
我正在使用SQL Server 2012。
预期结果将类似于以下内容:
如何在这里获得预期的结果?
生成测试数据的脚本:
CREATE TABLE [#tmp_data]
(
[visitor] INT,
[visit_id] INT,
[visit_time] DATETIME,
[val] numeric(4,2),
[purchase] BIT
);
INSERT INTO #tmp_data( visitor, visit_id, visit_time,val, purchase )
VALUES( 1, 1001, '2020-01-01 10:00:00', 0.23,0 ),
( 1, 1002, '2020-01-02 11:00:00', 0.97,1 ),
( 1, 1003, '2020-01-02 14:00:00', 0.55, 1 ),
( 2, 2001, '2020-01-01 10:00:00', 0.11, 1 ),
( 2, 2002, '2020-01-07 11:00:00', 0.57, 0 ),
( 2, 2003, '2020-01-08 14:00:00', 0.16, 0 ),
( 2, 2004, '2020-01-11 14:00:00', 0.38, 1 );
在SQL Server中,一个选项使用横向联接:
select t.*, x.percent_val
from #tmp_data t
cross apply (
select exp(sum(log(t1.val))) percent_val
from #tmp_data t1
where t1.visitor = t.visitor and t1.visit_time > dateadd(day, - 7, t.visit_time) and t1.visit_time <= t.visit_time
) x
where t.purchase = 1
横向连接可恢复同一位访客最近7天的访问。然后,我们使用算术来计算该值的总积(只要val
大于,它就起作用0
)。
访客| visit_id | visit_time | val | 购买| percent_val ------:| -------:| :---------------------- | ---::------- | ----------: 1 | 1002 | 2020-01-02 11:00:00.000 | 0.97 | 是的 0.2231 1 | 1003 | 2020-01-02 14:00:00.000 | 0.55 | 是的 0.122705 2 | 2001 | 2020-01-01 10:00:00.000 | 0.11 | 是的 0.11 2 | 2004 | 2020-01-11 14:00:00.000 | 0.38 | 是的 0.034656
如果还要处理0
值,则可以更改select
suquery的子句:
select case when min(val) = 0
then 0
else exp(sum(log(case when val > 0 then t1.val end)))
end percent_val
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句