如何根据SQL

时间:2015-10-07 13:21:22

标签: sql

有没有办法根据SQL中的其他列类型计算行数?

数据库:

Department | Resource Type | People
===================================
HR         | manager       | john
           | staff         | jason
           | staff         | smith
IT         | manager       | wendy
           | staff         | emma
           | staff         | jay
           | staff         | cody
HR2        | manager       | john
           | staff         | terry
           | staff         | mike
           | staff         | fry

预期产出:

john, 5 employees
wendy, 3 employees

谢谢

4 个答案:

答案 0 :(得分:1)

使用交叉点很容易完成。这也需要一个为两个不同部门的经理工作的员工,以及一个有多个经理的部门。

SELECT t1.People as ManagerName, 
    count(distinct t2.People) 
FROM @Staff t1 
LEFT JOIN @Staff t2 ON t2.Department = t1.department 
    AND t2.ResourceType = 'staff' WHERE t1.ResourceType = 'manager'
GROUP BY t1.People

答案 1 :(得分:1)

与其他答案一样,我还必须假设所有行都在Department列中有一个值。否则,就没有办法做你想要的了。

此外,您的示例数据似乎暗示每个部门只有一名经理。所以我也会做出这样的假设。

执行此操作的简单查询是:

select mgr.people || ', ' ||
       count(staff.people) || ' employees' -- the string concatenation on these lines may vary depending on your database.
  from TableName mgr
  left join TableName staff
    on staff.Department = mgr.Department
   and staff.ResourceType = 'staff'
 where mgr.ResourceType = 'manager'
 group by mgr.people

答案 2 :(得分:0)

根据您的数据样本,尝试:

SELECT S.Department,
       (SELECT TOP 1 SUB.People FROM dbo.Staff SUB
        WHERE SUB.Department = S.Department 
        AND SUB.ResourceType = 'manager') as Manager,
       COUNT(*) as Employees FROM dbo.Staff S
   WHERE S.ResourceType = 'staff'
   GROUP BY S.Department

我在这里假设Department将包含每条记录的值,而不仅仅是管理者,每个部门至少有一位经理。

{{3}}

答案 3 :(得分:0)

您可以通过创建2个临时表来执行此操作:

select People, sum(quantity) from(
select [ResourceType], People,quantity
from tablename
right join
(
select Count(Department) quantity, Department
from tablename
group by [ResourceType], Department
having [ResourceType] = 'staff') tmp1 on tablename.Department = tmp1.Department
where [ResourceType] = 'Manager'
) tmp2 
group by People