旋转以用 1 和 0 计算平均值

Pivoting to calculate average with 1's and 0's

我需要帮助从如下所示的数据集构建数据透视查询:

1 表示员工与某人或地点交谈,0 表示他们没有与某人交谈

我想 return 计算与员工和经理交谈过的联系人的百分比以及与经理交谈过的位置的百分比,因此 table 看起来像这样:

关于如何调整它以便计算每个员工的指定联系人的百分比,然后计算每个经理的员工的指定联系人的百分比,有什么想法吗?

如果您只有两个类别,则不需要数据透视表。尝试案例语句:

Select employee as [Name]
  ,count(case when ContactType = 'Individual' and SpokeTo = 1 then LocationName end) * 100.0/ NULLIF(count(case when ContactType = 'Individual' then LocationName end), 0) as IndividualContacts
  ,count(case when ContactType = 'Location' and SpokeTo = 1 then LocationName end) * 100.0/ NULLIF(count(case when ContactType = 'Location' then LocationName end), 0) as LocationContacts
from MyTable
group by Employee

请注意 *100.0 对于避免整数除法很重要(或者您可以显式转换为 decimal)。 NULLIF 是可选的,除非您有一些员工没有分配任何一种或另一种类型的联系人 - 然后您必须包括它以避免除以 0 错误。