SQL Server中的转换率(子查询)
问题描述:
我有一个销售数据,其中有三个类别,分别是赢得,丢失和开放的阶段。SQL Server中的转换率(子查询)
我想写一个转换率的查询。从舞台上获得的金额除以赢得的金额+失去一个销售代表。销售代表共有50个阶段胜利和120(阶段赢得和失去)。所以我的查询应该执行50/120。请图像链接数据。
select
id, sum(sales)
from
df
where
id = '123'
and stage ='won'
group by
id
having
sum(sales)/(select sum(sales)
from df
where stage = 'Won' OR stage = 'Lost')
我从此查询中收到错误。不知道如何得到答案。 enter image description here
答
也许这就是你想要什么:
select id,
sum(case when stage = 'won' then sales end) * 1.0/sum(sales)
from your_table
where stage in ('won', 'lost')
group by id;
如果denomintor可以是0,使用NULLIF
零错误,避免分裂和返回null代替。
select id,
sum(case when stage = 'won' then sales end) * 1.0/nullif(sum(sales), 0)
from your_table
where stage in ('won', 'lost')
group by id;
您使用的是SQL Server吗?你能否提供一些样本数据和预期结果? – GurV
在问题中请。还要添加预期的输出。 – GurV