2017-05-14 130 views
0

我有一个销售数据,其中有三个类别,分别是赢得,丢失和开放的阶段。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

+1

您使用的是SQL Server吗?你能否提供一些样本数据和预期结果? – GurV

+1

在问题中请。还要添加预期的输出。 – GurV

回答

1

也许这就是你想要什么:

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; 
+0

嘿谢谢。查询执行。一切工作正常 – Nirmal

+0

@Nirmal - 请** [编辑](http://stackoverflow.com/posts/43967593/e​​dit)**您的问题,并添加**示例数据和预期结果**。 – GurV