计算SQL中supportnumber的进度

时间:2017-09-28 11:22:23

标签: sql sql-server

Microsoft SQL Server 2016

我得到了下表:

|------------------------|------------------|-------|
|      Supportnumber     |     Closed       |  Time |
|------------------------|------------------|-------|
|          1234          |         0        |   90  | 
|          1234          |         1        |   120 |
|          1234          |         1        |   30  |
|          1248          |         1        |   20  |
|          1248          |         0        |   100 | 
|          1256          |         1        |   10  |
|          1256          |         0        |   50  |
|------------------------|------------------|-------|

每一行都可以看作是一项活动。例如"安装软件"。但是对于这个例子,我没有包括这个活动的摘要。

其中Supportnumber是每个支持呼叫的唯一编号。 Closed定义此支持编号内的活动是否已完成。已结束= 1。已关闭= 0未完成。时间是每项活动的持续时间。

现在,我想看看这个支持数量的进展情况。 所以在示例Supportnumber = 1234

Total time = (90+120+30)=240
Finished time = (120+30)=150
Percentage finished = (150/240)*100=62.5%

所以请求的结果是:

|------------------------|------------------|
|      Supportnumber     |     Percentage   |
|------------------------|------------------|
|          1234          |         62,5     | 
|          1248          |         16,7     |
|------------------------|------------------|

我确实没有使用SQL经验。但不是一个完整的新手。我尝试了CASE的一些陈述,但我仍然无法弄清楚它是如何工作的。任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select supportnumber,
       sum(case when closed = 1 then time else 0.0 end) / sum(time) as finished_ratio
from t
group by supportnumber;

如果您希望将其作为0到100之间的数字,则乘以100.

如果要在聚合后进行过滤,请使用having子句:

having sum(closed) > 0

答案 1 :(得分:1)

SELECT Supportnumber, (SUM (Closed * Time * 1.0) / SUM (Time) ) * 100 Percentage
    FROM YOURTABLE
GROUP BY Supportnumber;

答案 2 :(得分:0)

尝试此查询可能会帮助您。

select * into #status from (
select 1234 as Supportnumber ,0 closed ,90 time
union all
select  1234,1,120
union all
select 1234, 1,30
union all
select 1248 ,1,20
union all
select 1248,0,100
union all
select 1256, 1,10
union all
select 1256,0,50
)as a 

;with cte as (
select distinct Supportnumber,
cast(SUM(time) OVER (partition by Supportnumber ORDER BY Supportnumber range UNBOUNDED PRECEDING) as float)Total_time,
cast(SUM(case when closed =1 then time else 0 end) OVER (partition by Supportnumber ORDER BY Supportnumber range UNBOUNDED PRECEDING)as float) Finished_time from #status
)
select Supportnumber,round((Finished_time/Total_time)*100,1) Percentage from cte