没有嵌套选择的计数:这可能吗?

时间:2015-03-25 07:20:13

标签: sql count sql-optimization

数据库:

Department  Position             Points
    A        Manager               50
    A        Supervisor            10
    A        Supervisor            10
    A        Staff                 2
    A        Staff                 2
    B        Manager               40
    B        SuperVisor            8
    B        Staff                 2
    B        Staff                 2
    B        Staff                 2

所需的查询结果:

Dept  Manager Count  Supervisor Count  Staff Count    Staff Total Pts   

A        1                  2              2                 4
B        1                  1              3                 4

如果不使用带有count的嵌套选择,是否可以获得所需的查询结果?

我们使用嵌套计数有一个类似的存储过程,我们希望使其更简单,更好/更快地执行

3 个答案:

答案 0 :(得分:0)

使用Conditional Aggregate仅计算特定数据

Select Department,
       count(case when Position = 'Manager' then 1 END) as Manager,
       count(case when Position = 'Supervisor' then 1 END) as Supervisor,
       count(case when Position = 'Staff' then 1 END) as Staff
From yourtable
Group by Department

如果您使用的是Sql Server,请使用此

SELECT Department,
       Manager,
       Supervisor,
       Staff
FROM   Yourtable
       PIVOT (Count(Position)
             FOR Position IN (Manager,Supervisor,Staff))pv 

答案 1 :(得分:0)

使用条件SUM

SELECT Department,
       SUM(CASE WHEN Position = 'Manager' THEN 1 END) as Manager,
       SUM(CASE WHEN Position = 'Supervisor' THEN 1 END) as Supervisor,
       SUM(CASE WHEN Position = 'Staff' THEN 1 END) as Staff
FROM yourtable
GROUP BY Department

答案 2 :(得分:0)

或者你可以使用PIVOT算子:

select Detartment, Manager, Supervisor, Staff
from yourtable
pivot (count(Position) for Position in (Manager, Supervisor, Staff)) Result