更有效的方式来写这个查询?根据不同的条件来获取记录计数

问题描述:

让我表说我有列:更有效的方式来写这个查询?根据不同的条件来获取记录计数

Store, Region, Name, EmployeeType 

而且有s个员工类型:

Regular, Contractor 

我希望得到一个计数每个商店,区域组合中有多少常规和承包商类型的员工。

目前我有此查询代码:

select distinct Store, Region, RegularCount, ContractorCount 
from shop s 
left join (
    select Store, Region, count(*) as RegularCount 
    from shop 
    where employeetype like 'regular' 
) rc 
on rc.store = s.store and rc.region = s.region 
left join (
    select Store, Region, count(*) as ContractorCount 
    from shop 
    where employeetype like 'conctractor' 
) cc 
on cc.store = s.store and cc.region = s.region 

我想知道如果有一个更有效的方式来做到这一点? 因为如果有更多的员工类型,那么我将不得不增加我的子查询的数量,这是不可扩展的。

我看着count(*)超过但我不认为这是在这种情况下去的路?

note: 建议的复制帖子不能解决我的“可伸缩性”问题。

+1

的可能的复制[计数基于SQL Server中的条件(http://*.com/questions/3455201/count-based-on-condition -in-sql-server) –

+0

如果你想要一个可伸缩的方式,我认为你可以在子查询中实际使用解析函数(count(*)over(partiotion by ...),然后对其结果进行分组并将其连接起来,您不会为每个“employeetype”获得单独的列,而是将所有内容都放在一列中,例如:“conctractor:5; regular:12”等 – Demo

+0

您的子查询缺少“group by”。如果代码实际上是一个疏忽 –

只需使用条件汇总:

select Store, Region, 
     sum(case when employeetype like 'regular' then 1 else 0 end) as RegularCount, 
     sum(case when employeetype like 'contractor' then 1 else 0 end) as ContractorCount 
from shop 
group by Store, Region; 

如果你有数目不详的employeetype值,然后把一个在每一行:

select Store, Region, employeetype, COUNT(*) 
from shop 
group by Store, Region, employeetype; 
+0

非常感谢你!这绝对有帮助,但我寻找一种更具扩展性的方式,因为他们会自动抓住employeetype并计数? – alwaysaskingquestions

看看这符合你的需求,这不是”吨有多列输出,但像其他答案一样。我发现使用SQL输出动态添加数据行与列是更容易的。否则动态SQL可能需要动态添加列。

select 
    Store, 
    Region, 
    employeetype, 
    COUNT(employeetype) AS CountOfEmplType 
from shop 
group by Store, Region, employeetype; 

这将是less效率比聚合查询,但也可以工作。

Select 
    DISTINCT 
    Store, 
    Region, 
    EmployeeType, 
    Count(*) over (partition by EmployeeType) 
from shop 
+1

窗口功能对此非常不需要。 OP不是“专注”。 –

+0

非常感谢您的解释,它绝对有帮助! – alwaysaskingquestions

我会添加另一列。我认为这会得到你想要的东西:

Select region, Store, Employeetype, Count(*) as tot_emp From shop Group by region, store, employeetype