【问题标题】:Using OVER to show a percentage使用 OVER 显示百分比
【发布时间】:2015-09-11 01:41:20
【问题描述】:

有人可以告诉我一种使用 OVER 完成以下任务的方法吗?

这就是我所拥有的

JobId     AgentID
--------------------------------------------
Job1      1
Job1      8
Job1      8
Job2      6
Job2      6
Job3      5

我需要列出每个作业的顶级代理并显示该作业在该代理上运行的百分比:

JobId     AgentID     TopPercent
--------------------------------------------
Job1      8           66
Job2      6           100
Job3      5           100

这需要通过计算行数来完成,因为实际上有数百个工作和代理。

顺便说一句,我正在使用 SQL 2008。

【问题讨论】:

  • 如果您有两个代理的百分比与 top 相同,例如 50/50,您要同时显示这两个代理怎么办?还是其中任何一个?
  • 这是一个很好的问题,EricZ。我个人不在乎,但下一个看到这个的人可能会。

标签: sql-server-2008 tsql


【解决方案1】:

你可以这样写……这里有一个例子:

create table test (jobid varchar(10), agentid int);

insert into test values
('job1',      1)
,('job1',      8)
,('job1',      8)
,('job2',      6)
,('job2',      6)
,('job3',      5);

-- using OVER
select distinct jobid, agentid, 
(count(*) over (partition by jobid, agentid))*100 /
(count(*) over (partition by jobid)) as TopPercent
from test

如果您不想使用 OVER,请尝试以下操作:

-- not using OVER
with 

jobcount as (
  select jobid, count(*) as totbyjob from test group by jobid
),

jobagentcount as (
  select jobid, agentid, count(*) as totbyjobagent
  from test
  group by jobid, agentid
)

select 
  jac.jobid, 
  jac.agentid, 
  totbyjobagent*100/totbyjob as TopPercent
from jobagentcount jac
inner join jobcount jc
  on jac.jobid = jc.jobid

示例 SQLFiddle:http://sqlfiddle.com/#!3/f867c/18

要按百分比只获得排名靠前的职位,这样的查询就足够了:

with percents as (
  select distinct jobid, agentid, 
  (count(*) over (partition by jobid, agentid))*100 /
  (count(*) over (partition by jobid)) as toppercent
  from test
)

select jobid, agentid, toppercent from (
  select 
    percents.*,
    row_number() over(partition by jobid order by toppercent desc) as rank
  from percents
) main
where rank = 1

示例如下:http://sqlfiddle.com/#!3/f867c/27

【讨论】:

  • 这是百分比 - 不仅仅是最高百分比。但它很光滑。 +1
  • 是的,唯一的问题是您回答的过度版本会返回所有带百分比的行,而我只需要返回最高百分比的行。不过关闭。
  • 我添加了一个返回最高百分比的查询版本
猜你喜欢
  • 2021-12-01
  • 2018-03-12
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
相关资源
最近更新 更多