0

我正在尝试获取他们工作的销售人员的数据。我正在使用 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 

此查询的问题是它只产生一个区域。但是,有些销售人员在多个地区工作……我需要把他们全部找出来。

对此的任何帮助将不胜感激。

4

1 回答 1

0

您必须意味着您想知道员工随着时间的推移在哪里工作。据我在 AdventureWorks2008 和 AdventureWorks2008R2 中看到的,Sales.SalesPerson 被分配了一个 TerritoryID,然后在 Sales.SalesTerritoryHistory 中,每个 BusinessEntityID 可以有多个 TerritoryID。对于那些数据库,使用这个:

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 :)

于 2013-07-30T22:59:16.040 回答