有一个发票表,其中包含创建发票的人。一个人可以属于多个办公室,每个人只能有一个主要办公室,但同一个人可以在每个办公室担任多个角色。
declare @person table (personid int)
declare @office table (officeid int, officename varchar(10))
declare @personoffice table (personid int, officeid int, mainoffice bit, personrole varchar(10))
declare @invoice table (personid int)
insert into @person values (1), (2), (3), (4)
insert into @office values (1, 'office1'), (2, 'office2'), (3, 'office3'), (4, 'office4')
insert into @personoffice values (1, 1, 1, 'role1'), (1, 1, 1, 'role2'), (1, 2, 0, 'role1'), (1, 3, 0, 'rolex'), (2, 2, 1, 'role1'), (2, 2, 1, 'role2'), (2, 3, 0, 'rolex'), (3, 3, 1, 'role1'), (3, 4, 0, 'role2')
insert into @invoice values (1), (1), (1), (2), (2), (3), (3), (3), (3), (3)
因此,在这个例子中,我们有 3 个人,他们属于多个办公室,但每个办公室只有一个主要办公室,但有些人每个办公室有多个角色。他们各自创建了多张发票。
我可以通过以下方式获取每人的发票数量:
select
i.personid,
count(*) InvoiceCountByPerson
from
@invoice i
inner join
@person p on p.personid = i.personid
group by
i.personid
返回:
personid InvoiceCountByPerson
--------------------------------
1 3
2 2
3 5
我需要按主要办公室名称获取发票数量。主要办公室为office1的Person1创建了3张发票,主要办公室为office2的Person2创建了2张发票,主要办公室为office3的Person3创建了5张发票,因此预期结果:
officename InvoiceCountByOfficeName
------------------------------------
office1 3
office2 2
office3 5
这不起作用:
select
o.officename,
count(*) InvoiceCountByOfficeName
from
@invoice i
inner join
@person p on p.personid = i.personid
inner join
@personoffice po on po.personid = p.personid AND po.mainoffice = 1
inner join
@office o on o.officeid = po.officeid
group by
o.officename
返回时:
officename InvoiceCountByOfficeName
-------------------------------------
office1 6
office2 4
office3 5
由于同一个人有多个具有不同角色的 mainoffice = 1 记录,我需要在 @personoffice 连接上有某种不同的记录。也有数百万张发票,因此需要考虑性能。
最佳答案
您已经很接近了...您所要做的就是使用派生表,而不是直接使用 @personoffice
表:
select
o.officename,
count(*) InvoiceCountByOfficeName
from
@invoice i
inner join
@person p on p.personid = i.personid
inner join
(
select distinct personid, officeid
from @personoffice
where mainoffice = 1
)
po on po.personid = p.personid
inner join
@office o on o.officeid = po.officeid
group by
o.officename
结果:
officename InvoiceCountByOfficeName
---------- ------------------------
office1 3
office2 2
office3 5
关于SQL Server 2012 : how to get count group by from multiple table joins,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38114577/