SQL Server总计总计

时间:2019-05-01 09:52:48

标签: sql-server

在我的SQL Server查询中,我试图计算每个站点的员工人数。这可行,但是当我尝试添加总计的百分比时,它仍然按网站分组,因此不准确。

有没有更简单的方法来实现这一目标?

我正在使用此查询创建视图。

select Site.SiteName,
sum(case when Employee.ActiveStatus = 'Yes' then 1 else 0 end) as 
"NumberOfEmployees",
CONVERT(decimal(6,2),(sum(case when Employee.ActiveStatus = 'Yes' then 1 
else 0 end))/(convert(decimal(6,2),COUNT(EmployeeID)))) as PercentageOfEmps

from Employee
left join Site
on(Employee.SiteID=Site.SiteID)
GROUP BY Site.SiteName;
GO

4 个答案:

答案 0 :(得分:3)

您可以使用子查询:

select 
  Site.SiteName,
  NumberOfEmployees = sum(case when Employee.ActiveStatus = 'Yes' then 1 else 0 end),
  PercentageOfEmps = CONVERT(decimal(6,2),(sum(case when Employee.ActiveStatus = 'Yes' then 1 
else 0 end))/(SELECT COUNT(EmployeeID) FROM Employee)
from Employee
left join Site
  on Employee.SiteID=Site.SiteID
GROUP BY Site.SiteName;

答案 1 :(得分:0)

由于无法使用任何示例数据,因此我无法为您提供解决方案,因此我提供了一个小的数据集。

一种方法是使用CTE /子查询获取总数,然后将总数包括在GROUP BY中。此方法避免对表进行2次扫描:

WITH VTE AS(
    SELECT *
    FROM (VALUES(1,'Steve',1),
                (2,'Jayne',1),
                (3,'Greg',2),
                (4,'Sarah',3)) V(EmpID, EmpName, SiteID)),
CTE AS(
    SELECT V.EmpID,
           V.EmpName,
           V.SiteID,
           COUNT(V.EmpID) OVER () AS TotalCount
    FROM VTE V)
SELECT C.SiteID,
       COUNT(C.EmpID) AS Employees,
       COUNT(C.EmpID) / (C.TotalCount *1.0) AS Perc
FROM CTE C
GROUP BY C.SiteID,
         C.TotalCount;

答案 2 :(得分:0)

此脚本应提供帮助-

SELECT 
Site.SiteName,
COUNT(EmployeeID) AS [NumberOfEmployees],
((COUNT(EmployeeID)*1.0)/(SELECT COUNT(*) FROM Employee WHERE ActiveStatus = 'Yes'))*100.00 as PercentageOfEmps
FROM Employee
INNER JOIN Site
    ON Employee.SiteID = Site.SiteID
WHERE Employee.ActiveStatus = 'Yes'
GROUP BY Site.SiteName;

答案 3 :(得分:0)

数据创建脚本     declare @Employee Table(EmployeeID int ,ActiveStatus nvarchar(20) ,SiteID int) declare @Site Table(SiteName nvarchar(20) ,SiteID int) insert into @Employee values(1,'Yes',101),(2,'Yes',101),(3,'Yes',102),(4,'Yes',102), (5,'Yes',101)

insert into @Site values('Site1',101)
insert into @Site values('Site2',102)

//真实脚本以获取%percentage ;with cte as ( select s.SiteName,sum(case when e.ActiveStatus = 'Yes' then 1 else 0 end) as "NumberOfEmployees" from @Employee e left join @Site s on(e.SiteID=s.SiteID) GROUP BY s.SiteName ), cte_sum as (select sum(NumberOfEmployees) as total from cte ) select c.*, convert (decimal(6,2),c.NumberOfEmployees)/convert (decimal(6,2),cs.total)*100 from cte_sum cs, cte c;