使用Adventureworks2014,未正确加入

时间:2016-06-09 18:32:18

标签: sql sql-server join

使用SqlServer 2014.

以下是我的好坏代码。我正在尝试查询HumanResources.Employee数据库,并在其中包含两个内容,最新的付费升级来自HumanResources.EmployeePayHistory,形式为"最近的日期"和第一,中间和Person.Person文件中的姓氏。

我能够查询员工数据并成功包含名称。

select b.*,(a.FirstName +' '+ isnull(a.MiddleName,'')+' '+a.LastName) as WHOLE_NAME
from Person.Person a
join HumanResources.Employee b
on a.BusinessEntityID = b.BusinessEntityID 

然后我能够弄清楚如何从付费历史文件中获取正确的日期格式......

Select Convert(VarChar(10),ModifiedDate,101) as Date 
From HumanResources.EmployeeDepartmentHistory

我知道我可以找到每次付费升级的MAX日期:

Select BusinessEntityID, MAX(ModifiedDate) as MostRecent
From HumanResources.EmployeePayHistory
Group By BusinessEntityID

但是当我尝试将三张桌子组合在一起时,我的大脑几乎融化了,我一直在吹它。这是我的烂摊子:

Select Convert(VarChar(10),c.ModifiedDate,101) as Date, b.*,(a.FirstName +' '+ isnull(a.MiddleName,'')+' '+a.LastName) as WHOLE_NAME
From Person.Person a inner join
HumanResources.Employee b on a.BusinessEntityID = b.BusinessEntityID
inner join 
(Select BusinessEntityID, MAX(ModifiedDate) as MostRecent
From HumanResources.EmployeePayHistory
Group By BusinessEntityID)
HumanResources.EmployeePayHistory c
on c.businessEntityID = a.BusinessEntityID

你能帮我解决这个最后的三桌加入尝试吗? 非常感谢。

2 个答案:

答案 0 :(得分:1)

  • 将此Convert(VarChar(10),c.ModifiedDate,101) as Date更改为此Convert(VarChar(10),c.MostRecent,101) as Date(因为您已将您引用的列命名为as MostRecent
  • 将您的派生表联接中的别名更改为c

整个查询:

SELECT Convert(VarChar(10),c.MostRecent,101) as Date, 
       b.*,
      (a.FirstName +' '+ isnull(a.MiddleName,'')+' '+a.LastName) as WHOLE_NAME
FROM Person.Person a 
INNER JOIN HumanResources.Employee b on a.BusinessEntityID = b.BusinessEntityID
INNER JOIN (SELECT BusinessEntityID, MAX(ModifiedDate) as MostRecent
            FROM HumanResources.EmployeePayHistory
            GROUP BY BusinessEntityID
           ) c on c.businessEntityID = a.BusinessEntityID

答案 1 :(得分:0)

我认为你是在思考这个问题。你可以做两个简单的连接,然后MAX()从薪资历史表中最后一次加薪。我认为您不需要触摸员工部门历史表。

SELECT c.*
    , a.businessentityid
    , FirstName + ISNULL(middlename, '') + lastname AS fullname
    , CONVERT(VARCHAR(10), MAX(b.ratechangedate), 101) AS last_pay_increase
FROM person.person a
INNER JOIN HumanResources.EmployeePayHistory b
    ON b.BusinessEntityID = a.BusinessEntityID
INNER JOIN HumanResources.Employee c
    ON c.BusinessEntityID = a.BusinessEntityID
GROUP BY c.BusinessEntityID
    , c.NationalIDNumber
    , c.LoginID
    , c.OrganizationNode
    , c.OrganizationLevel
    , c.JobTitle
    , c.BirthDate
    , c.MaritalStatus
    , c.Gender
    , c.HireDate
    , c.SalariedFlag
    , c.VacationHours
    , c.SickLeaveHours
    , c.CurrentFlag
    , c.rowguid
    , c.ModifiedDate
    , a.businessentityid
    , FirstName + ISNULL(middlename, '') + lastname