Sql server 2008 使用OVER显示百分比
有人能告诉我一种方法来完成以下任务吗 这就是我所拥有的Sql server 2008 使用OVER显示百分比,sql-server-2008,tsql,Sql Server 2008,Tsql,有人能告诉我一种方法来完成以下任务吗 这就是我所拥有的 JobId AgentID -------------------------------------------- Job1 1 Job1 8 Job1 8 Job2 6 Job2 6 Job3 5 我需要列出每个作业的顶级代理,并显示该作业在该代理上运行的百分比: JobId AgentID TopPercent -------------------
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。您可以编写如下内容……下面是一个示例:
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
如果您不想过度使用,请尝试以下方法:
-- 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示例:
要按百分比仅获得排名靠前的工作,这样的查询就足够了:
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
示例如下:这是百分比,而不仅仅是最高百分比。但它是光滑的+1是的,唯一的问题是,您答案的over版本返回所有带有百分比的行,我只需要返回顶部的百分比行。但是关闭。我添加了一个查询版本,该版本将返回top percentage如果您有两个代理的百分比与top相同,例如50/50,您想同时显示这两个代理吗?或者只是其中的一个?这是个好问题EricZ。我个人不在乎,但下一个看这个的人可能会。