按最早时间列出行顺序

时间:2019-05-31 12:54:27

标签: sql sql-server tsql

我在sql中有些新知识,我有这个问题要从三个表中获取特定信息。我有那三个桌子。

员工表

enter image description here

公司表

enter image description here

就业表

enter image description here

在职员工编号为FK 公司中的CompanyID为FK Employment中的EmploymentID为PK EmploymentEndDate中的EmploymentEndDate表示该工人当前正在那里工作。

我一直在尝试,但是没有用

select Company.CompanyName as CompanyName , CONCAT( Employee.FirstName, ' ' ,Employee.LastName) as EmployeeName , Employment.EmploymentStartDate from Employment LEFT JOIN Employee on Employee.EmployeeID = Employment.EmployeeID 
LEFT JOIN Company on Company.CompanyID = Employment.CompanyID 
where Employment.EmploymentEndDate is null 
and EXISTS(SELECT Employment.CompanyID, MAX(DATEDIFF( DAY,Employment.EmploymentStartDate ,GETDATE())) as MaxDate FROM  Employment where  Employment.EmploymentEndDate is null group by CompanyID)

并给我这个结果:

enter image description here

这是错误的,因为从“ Steve's Widgets Inc”公司开始,我希望只有John Doe是最老的工人。

这正是我想要的,列出所有公司,并提供在公司工作的雇员的姓名和开始日期,这是目前在该公司工作的雇员中最长的。 (预期列:CompanyName,EmployeeName,EmploymentStartDate)

2 个答案:

答案 0 :(得分:0)

with oldest (companyId, empStart) as 
(
select companyId, min(EmploymentStartDate) 
from Employment
where EmploymentEndDate is null
group by companyId
)
select c.CompanyName, e.Firstname + ' ' + e.LastName as employeeName, em.employmentStartDate
from Employment em
inner join oldest o on em.CompanyId = o.CompanyID and em.employmentStartDate = o.empStart
inner join employee e on em.EmployeeId = e.EmployeeId
inner join company c on em.CompanyId = c.CompanyId;

答案 1 :(得分:0)

如果要使用第一个值,它将看起来像这样,请注意,我没有在sql服务器上使用第一个值(仅在db2上),并且由于没有手头的sql服务器,所以我没有对其进行测试。

SELECT DISTINCT
  Company.CompanyName, 
  CONCAT(Employee.FirstName, ' ', Employee.LastName) AS EmployeeName,
  FIRST_VALUE(Employment.EmploymentStartDate) 
    OVER (PARTITION BY Company.CompanyName, CONCAT(Employee.FirstName, ' ', Employee.LastName) 
      ORDER BY Employment.EmploymentStartDate ASC 
      RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
    ) AS StartDate
FROM Employment 
JOIN Company ON Employment.CompanyID = Company.CompanyID
JOIN Employee ON Employment.EmployeeID = Employee.EmployeeID
WHERE Employment.EmploymentEndDate IS NULL