SQL查询:计算每个用户每月每个总数的百分比

时间:2019-01-30 20:35:51

标签: sql sql-server

以下查询为我提供了下面的前四列:

 declare @begindate DateTime,
        @enddate DateTime 

Select @begindate =Dateadd(month,datediff(month,0,getdate())-3,0)
      ,@enddate=EOMONTH(Dateadd(month,datediff(month,0,getdate())-1,0))
select p.username 'Approver'
,p.Code 'Status'
, count(p.PaymentRequestId) 'Monthly Count' 
,Datename(Month,p.max_date) 'Month'

from 
       (
        select  su.UserName,pr.PaymentRequestId,prs.Code ,max(pr.CreateDateTime) 'Max_Date' 
        from PaymentRequestStatusHistory pr
        inner join hydradb..SystemUser su on pr.systemuserid = su.SystemUserId
        inner join hydradb..PaymentRequestStatus prs on prs.PaymentRequestStatusid = pr.PaymentRequestStatusid
        where 1=1 
        and (convert(date,pr.CreateDateTime)  BETWEEN @begindate
            AND DATEADD(ms, - 2, DATEADD(dd, 1, DATEDIFF(dd, 0, @enddate))))
        and pr.PaymentRequestStatusId in (3,4)
        and su.systemuserid in ( 414, 336, 12)
        group by su.UserName,pr.PaymentRequestId,prs.Code
        )p
group by p.UserName,p.Code,  Datename(Month,p.max_date)
order by p.UserName,p.code

现在,我必须创建一个附加列,以计算每个用户每个状态每月每个“月计数”总数的百分比。例如:在12月, 每月计数为2786(mrob批准为2785,rsimm批准为1),我需要计算每月总数的百分比。去年12月,mrob批准了99.96%,rsimm批准了0.035%。

就像下面的这些

![在此处输入图片描述] [1]

2 个答案:

答案 0 :(得分:0)

您可以使用窗口功能:

select . . . ,
       count(*) as cnt,
       count(*) * 1.0 / sum(count(*)) over (partition by Datename(Month, p.max_date), status) as ratio

答案 1 :(得分:0)

您需要使用窗口函数按月对总计进行分组,然后使用该数量在行中除以计算值。我不完全确定所提供的代码是否可以像无法测试的那样工作,但应该与之类似:

DECLARE @begindate DateTime,
        @enddate DateTime 

SELECT @begindate = Dateadd(month,datediff(month,0,getdate())-3,0)
      ,@enddate   = EOMONTH(Dateadd(month,datediff(month,0,getdate())-1,0))

SELECT p.username 'Approver'
      ,p.Code 'Status'
      ,count(p.PaymentRequestId) 'Monthly Count' 
      ,Datename(Month,p.max_date) 'Month'
      ,count(p.PaymentRequestId)/Count(p.PaymentRequestID) 
       OVER (PARTITION BY Datename(Month,p.max_date)) AS 'Percentage'
FROM 
       (
        select  su.UserName,pr.PaymentRequestId,prs.Code ,max(pr.CreateDateTime) 'Max_Date' 
        FROM PaymentRequestStatusHistory pr
        INNER JOIN hydradb..SystemUser su on pr.systemuserid = su.SystemUserId
        INNER JOIN hydradb..PaymentRequestStatus prs 
        on prs.PaymentRequestStatusid = pr.PaymentRequestStatusid
        WHERE 1=1 
        AND (convert(date,pr.CreateDateTime)  BETWEEN @begindate
        AND DATEADD(ms, - 2, DATEADD(dd, 1, DATEDIFF(dd, 0, @enddate))))
        AND pr.PaymentRequestStatusId in (3,4)
        AND su.systemuserid in ( 414, 336, 12)
        GROUP BY su.UserName,pr.PaymentRequestId,prs.Code
        ) p
GROUP BY p.UserName,p.Code,  Datename(Month,p.max_date)
ORDER BY p.UserName,p.code;