SQL百分比计算

时间:2015-04-08 14:47:16

标签: sql-server pivot-table

在SQL中是否可以计算“StaffEntered”列的“是”值(计算列的情况)在该用户的总订单总数中的百分比(RequestedBy)?我现在基本上在Excel中使用Pivot表执行此功能,但认为将其构建到查询中可能更容易。以下是现有的示例SQL代码:

    Select 
    Distinct

    RequestedBy = HStaff.Name,
    AccountID = isnull(pv.AccountID, ''),
    StaffEntered = Case When DictionaryItem2.Name like '%PLB%' Then 'Yes' Else 'No' end


FROM
 [dbo].[HOrd] HOrd WITH ( NOLOCK )
 left outer join HStaff HStaff with (nolock)
  on HOrd.Requestedby_oid = HStaff.ObjectID
  and HStaff.Active = 1
 left outer join DictionaryItem DictionaryItem2 WITH (NOLOCK)
  ON HSUser1.PreferenceGroup_oid = DictionaryItem2.ObjectID
  AND DictionaryItem2.ItemType_oid = 98

以下是我目前在Excel中使用查询结果所做的事情,我有一个数据透视表,我将“StaffEntered”字段的“是”值除以特定“RequestedBy”的总条目数“用户。基本上Excel正在进行汇总,然后我正在进行简单的除法计算以获得百分比。

enter image description here

提前致谢!

2 个答案:

答案 0 :(得分:1)

你没有提供很多详细信息,但我认为这应该与你正在寻找的非常接近。

select HStaff.Name as RequestedBy 
    , isnull(pv.AccountID, '') as AccountID 
    , Case When DictionaryItem2.Name like '%PLB%' Then 'Yes' Else 'No' end as StaffEntered 
    , sum(Case When DictionaryItem2.Name like '%PLB%' Then 1 Else 0 end) / GrandTotal
From SomeTable
group by HStaff.Name 
    , isnull(pv.AccountID, '')
    , GrandTotal

答案 1 :(得分:0)

给出SQL语句的FROM部分将允许我们创建更正确的答案。此语句将获得每个HStaff名称的yes / no总数,并将其添加到SQL语句中的每个详细记录中:

WITH    cte
          AS ( SELECT   HStaff.Name ,
                        SUM(CASE WHEN dictionaryItem2.Name LIKE '%PLB%' THEN 1
                                 ELSE 0
                            END) AS YesCount ,
                        SUM(CASE WHEN dictionaryItem2.Name NOT LIKE '%PLB%'
                                 THEN 1
                                 ELSE 0
                            END) AS NotCount
               FROM     YourTable
               GROUP BY HStaff.Name
             )
    SELECT  HStaff.Name AS requestedBy ,
            ISNULL(pv.AccountID, '') AS AccountID ,
            CASE WHEN DictionaryItem2.Name LIKE '%PLB%' THEN 'Yes'
                 ELSE 'No'
            END AS StaffEntered ,
            cte.YesCount / ( cte.YesCount + cte.NotCount ) AS PLB_Percentage
    FROM    yourtable
            INNER JOIN cte ON yourtable.Hstaff.Name = cte.NAME