这是我的第一个查询,它使用共享相同主键的两个表的表联接:
select s.Branch_ID, count(s.Branch_ID) 'No. of Staff', BranchName 'Branch Name'
from Sales_Staff s , Branch b
where s.Branch_ID = b.Branch_ID
group by s.Branch_ID, BranchName
order by 2 desc
这是第二个查询:
select p.Branch_ID, BranchName, Count(p.Branch_ID) 'Frequency of Packages bought'
from Payment p, Branch b
where p.Branch_ID = b.Branch_ID
Group by p.Branch_ID, BranchName
现在,两者的输出都是我期望和想要的。但是,当我使用相同的方法来连接这两个查询时,数字是错误的。
select p.Branch_ID, BranchName, Count(p.Branch_ID) 'Frequency of Packages bought', count(s.Branch_ID) 'No. of Staff'
from Payment p, Sales_Staff s, Branch b
where p.Branch_ID = s.Branch_ID
and s.Branch_ID = b.Branch_ID
Group by b.Branch_ID, p.Branch_ID, BranchName
错误的输出
任何帮助将不胜感激。
答案 0 :(得分:2)
由于您加入的人数越来越多-每个分支机构的每笔付款,每个员工都需要分别进行分组。
select b.BranchID, b.BranchName, isnull(s.StaffCount,0) as StaffCount, isnull(p.PackageCount,0) as PackageCount
from Branch b
left join (select Branch_ID, count(*) as StaffCount from SaleStaff group by Branch_ID) s on s.Branch_ID = b.Branch_ID
left join (select Branch_ID, count(*) as PackageCount from Payment group by Branch_ID) p on p.Branch_ID = b.Branch_ID