【问题标题】:Using a count as a percentage to determine results使用计数作为百分比来确定结果
【发布时间】:2022-09-24 19:28:03
【问题描述】:

我需要比较最近 12 小时内工作的 StatusID。如果该值超过 50%,则会创建警报。

select StatusID, count(statusid) as [count]
from job nolock 
where jobtypeid = 5033 
    and ModifiedOn > CONVERT(datetime,dateadd(hh,-12,getdate()),104)
group by statusid
order by 1 desc

这给了我我的结果,但我需要它作为:

CASE WHEN \"Count(StatusID = 5 > 50%)\" THEN \'\'GREEN\'\' ELSE \'\'RED\'\' 

如何将顶部的select 变成Case?

  • 你上面的例子中的分母是什么?而你只关心statusID 5? statusID 4 呢?
  • 4 是好的运行,5 是差的运行,所以所有可能的 StatusID 总数的 50% (1-7)

标签: sql


【解决方案1】:

请解释您将如何确定百分比? 如果您只想查看count(statusid)>50,那么:

select StatusID, count(statusid) as [count], (case when count(statusid)>50 then 'GREEN' else 'RED' end)
from job nolock 
where jobtypeid = 5033 
    and ModifiedOn > CONVERT(datetime,dateadd(hh,-12,getdate()),104)
group by statusid
order by 1 desc

【讨论】:

  • 所有可能的 StatusID (1-7) 的计数。如果该计数的 50% 是 StatusID = 5,then 'RED'
【解决方案2】:

尝试以下操作:

SELECT jobtypeid,  StatusID,
       CASE WHEN StatusID=5 AND 
                 CNT*1.0 /SUM(CNT) OVER (PARTITION BY jobtypeid)>0.5 
            THEN 'RED' ELSE 'GREEN'
       END AS Status5Result
  FROM
  (
    SELECT jobtypeid,  StatusID, 
       COUNT(*) CNT
    From job 
    WHERE jobtypeid = 5033 AND
          ModifiedOn > CONVERT(datetime,dateadd(hh,-12,getdate()),104)
    GROUP BY jobtypeid,  StatusID
  ) T
ORDER BY StatusID 

看到demo.

子查询查找jobtypeid 中每个StatusID 的计数,主查询使用求和窗口函数查找jobtypeid 中所有StatusID 计数的总和。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多