显示方程式结果

时间:2017-02-06 10:39:00

标签: sql sql-server

我想显示这个等式的结果(B / A + B)* 100

我不想要stage = 1的行和状态是开放的

A是stage = 1且状态丢失的行

B是stage = 2或更高的行,与状态无关

------------------------------------
 name |stage| state
------------------------------------
| ABC  | 1   | open
| DEF  | 1   | open 
| ABB  | 1   | lost
| ABD  | 1   | lost
| PQR  | 2   | won
| PQF  | 3   | lost 
| PQY  | 4   | open
| PQN  | 5   | won
| PQM  | 6   | lost
| PQM  | 7   | lost

结果应为(6/6 + 2)* 100 = 75%

2 个答案:

答案 0 :(得分:0)

SELECT
     [equation] =   CASE    
                        WHEN (ISNULL([a].[cnt], 0) + ISNULL([b].[cnt], 0)) = 0 THEN NULL
                        ELSE (ISNULL([b].[cnt], 0) / (ISNULL([a].[cnt], 0) + ISNULL([b].[cnt], 0))) * 100 
                    END             
FROM
    (
        SELECT  [cnt] = CAST(0 AS MONEY)
    )   AS [x]
OUTER APPLY
    (
        SELECT [cnt] = CAST(COUNT(*) AS MONEY) FROM [my_table] WHERE [stage] = 1 AND [state] = 'lost'  
    )   AS  [a]
OUTER APPLY
    (
        SELECT [cnt] = CAST(COUNT(*) AS MONEY) FROM [my_table] WHERE [stage] > 1
    )   AS  [b];

答案 1 :(得分:0)

不需要子查询或outer apply()

select [B/(A+B)]=
    (sum(case when stage >1 then 1.0 else 0.0 end)
        /
    sum(case 
           when stage =1 and state = 'lost' 
             then 1.0 
           when stage > 1
             then 1.0 
           else null 
           end))*100
from t

测试设置:http://rextester.com/THWUY43139

create table t (name char(3), stage int, state varchar(4))
insert into t values
   ('ABC',1,'open')
 , ('DEF',1,'open')
 , ('ABB',1,'lost')
 , ('ABD',1,'lost')
 , ('PQR',2,'won' )
 , ('PQF',3,'lost')
 , ('PQY',4,'open')
 , ('PQN',5,'won' )
 , ('PQM',6,'lost')
 , ('PQM',7,'lost');

查询:

select 
      [B]=sum(case when stage >1 then 1 else 0 end)
    , [(A+B)]=sum(case 
           when stage =1 and state = 'lost' 
             then 1
           when stage > 1
             then 1
           else 0
           end)
    , [B/(A+B)]=(sum(case when stage >1 then 1.0 else 0.0 end)
        /
        sum(case 
           when stage =1 and state = 'lost' 
             then 1.0 
           when stage > 1
             then 1.0 
           else null 
           end))*100
from t

结果:

+---+-------+----------+
| B | (A+B) | B/(A+B)  |
+---+-------+----------+
| 6 |     8 | 75,00000 |
+---+-------+----------+