[英]How to get date range between dates from the records in the same table?
I have a table with employment records.我有一张工作记录表。 It has Employee code, status, and date when table was updated.
它具有员工代码、状态和更新表的日期。 Like this:
像这样:
Employee![]() |
Status![]() |
Date![]() |
---|---|---|
001 ![]() |
termed![]() |
01/01/2020 ![]() |
001 ![]() |
rehired![]() |
02/02/2020 ![]() |
001 ![]() |
termed![]() |
03/03/2020 ![]() |
001 ![]() |
rehired![]() |
04/04/2021 ![]() |
Problem - I need to get period length when Employee was working for a company, and check if it was less than a year - then don't display that record.问题 - 当员工为公司工作时,我需要获取期间长度,并检查它是否少于一年 - 然后不显示该记录。
There could be multiple hire-rehire cycles for each Employee.每个员工可能有多个雇用-重新雇用周期。 10-20 is normal.
10-20是正常的。 So, I'm thinking about two separate selects into two tables, and then looking for a closest date from hire in table 1, to termination in table 2. But it seems like overcomplicated idea.
因此,我正在考虑将两个单独的选择放入两个表中,然后在表 1 中寻找从雇用到表 2 中终止的最接近的日期。但这似乎过于复杂的想法。
Is there a better way?有没有更好的办法?
Many approaches, but something like this could work:许多方法,但这样的事情可能会奏效:
SELECT
Employee,
SUM(DaysWorked)
FROM
(
SELECT
a1.employee,
IsNull(DateDiff(DD, a1.[Date],
(SELECT TOP 1 [Date] FROM aaa a2 WHERE a2.employee = a1.employee AND a2.[Date] > a1.[Date] and [status] <> 'termed' ORDER BY [Date] )
),DateDiff(DD, a1.[Date], getDate())) as DaysWorked
FROM
aaa a1
WHERE
[Status] = 'termed'
) Totals
GROUP BY
Totals.employee
HAVING SUM(DaysWorked) >= 365
Also using a CROSS JOIN is an option and perhaps more efficient.使用 CROSS JOIN 也是一种选择,而且可能更有效。 In this example, replace 'aaa' with the actual table name.
在此示例中,将“aaa”替换为实际的表名。 The IsNull deals with an employee still working.
IsNull 处理仍在工作的员工。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.