透视计算1和0的平均值

时间:2015-06-30 23:27:20

标签: sql sql-server tsql pivot-table

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

enter image description here

1表示员工与某人或某个位置交谈,0表示他们没有与某人交谈

我想要返回一个计算方法,说明员工和经理所说的联系人的百分比和所占位置的百分比,以便表格如下所示:

enter image description here

有关如何对此进行调整的任何想法,以便计算每个员工分配的联系人的百分比,然后计算每个经理的员工分配的联系人的百分比?

1 个答案:

答案 0 :(得分:1)

如果您只有两个类别,则不需要透视。尝试案例陈述:

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错误。