我正在尝试获取销售人员的数据w.r.t Territory他们的工作。我正在使用Adventureworks数据库表Employee,Contact,SalesPerson,SalesTerritory。
这是我的疑问:
Select p.FirstName, p.LastName, h.EmployeeID, t.Name as "Territory Name"
from Person.Contact p
INNER JOIN HumanResources.Employee h ON p.ContactID = h.ContactID
INNER JOIN Sales.SalesPerson s ON s.SalesPersonID = h.EmployeeID
INNER JOIN Sales.SalesTerritory t ON s.TerritoryID = t.TerritoryID
此查询的问题是它只产生一个Territory。但是,有销售人员在多个地区工作......我需要完成所有这些工作。
对此有任何帮助将不胜感激。
答案 0 :(得分:0)
您必须意味着您想知道员工在一段时间内的工作方式。据我在AdventureWorks2008和AdventureWorks2008R2中看到,Sales.SalesPerson被分配了一个TerritoryID,然后在Sales.SalesTerritoryHistory中,每个BusinessEntityID可以有多个TerritoryID。对于那些DB,请使用:
select p.FirstName
,p.LastName
,e.LoginID -- there is no EmployeeID in this version of AdventureWorks
,st.Name as [TerritoryName]
from Sales.SalesPerson as sp
join Person.Person as p
on p.BusinessEntityID = sp.BusinessEntityID
join HumanResources.Employee as e
on e.BusinessEntityID = sp.BusinessEntityID
join Sales.SalesTerritoryHistory as sth
on sth.BusinessEntityID = sp.BusinessEntityID
join Sales.SalesTerritory as st
on sth.TerritoryID = st.TerritoryID
-- keep the where clause if you want to find only current TerritoryIDs
-- remove the where clause if you want to know all across time
where GETDATE() between sth.StartDate and isnull(sth.EndDate,'9999-1-1')
澄清AdventureWorks DB的版本,我可以更正错误(但不要说2012,因为我没有安装SQL Server 2012:)