简体   繁体   English

如何从同一表中的记录中获取日期之间的日期范围?

[英]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 001 termed称为 01/01/2020 2020 年 1 月 1 日
001 001 rehired重新雇用 02/02/2020 2020 年 2 月 2 日
001 001 termed称为 03/03/2020 2020 年 3 月 3 日
001 001 rehired重新雇用 04/04/2021 2021 年 4 月 4 日

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.

相关问题 如何在SQL Server中获得给定日期的日期范围之间的日期 - How to get dates between a date range given a day in SQL Server 如何获取同一表中两个日期之间的替代日期并将这些日期插入临时表中? - How to get the alternate dates between two dates in the same table and insert those dates into a temporary table? 如何从表1中选择某些日期之间表2中没有记录的记录 - How to select records from table1 which doesnt have records in table 2 between certain dates 如何检查给定日期在表记录的范围内 - how to check given date is in range on table records 从由日期行组成的表中,如何计算日期在特定日期范围内的行数 - From a table of made up of rows of dates, how to count the number of rows where the date is in a certain date range 在给定日期范围内计数同一表中的不同记录 - Count distinct records in same table for given date range 在日期范围之间查找记录 - Find records IN BETWEEN Date Range 在两个日期范围之间需要Col 1的平均值,并从同一表更新Col 2 - Need Average of Col 1 between two date range and update Col 2 from same table 计算两个日期之间每个日期的记录数 - Calculate the number of records for each date between 2 dates 检查给定日期是否适合一系列日期 - Checking if a given date fits between a range of dates
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM