0

我有一个管理员工时间表的应用程序。

我的表看起来像:

TIMESHEET
  TIMESHEET_ID
  EMPLOYEE_ID
  etc

TIMESHEET_DAY:
  TIMESHEETDAY_ID
  TIMESHEET_ID
  DATE_WORKED
  HOURS_WORKED

每个时间表涵盖 14 天的时间段,因此每个 TIMESHEET 记录有 14 条 TIMESHEET_DAY 记录。如果有人去度假,如果在这 14 天期间没有工作时间,他们就不需要输入时间表。

现在,我需要确定员工在前 6 个月内是否有 7 天的空档。这意味着我必须查找 7 个连续的 TIMESHEET_DAY 记录,时间为 0 小时,或者 7 天的时间段(没有提交的记录和提交的工作时间为 0 小时的记录的组合)。在这种情况下,我需要知道最后一个 TIMESHEET_DAY 记录的 DATE_WORKED 和小时。

该应用程序是 asp.net,因此我可以检索所有 TIMESHEET_DAY 记录并遍历它们,但我认为必须有一种更有效的方法来使用 SQL 执行此操作。

4

2 回答 2

1
SELECT t1.EMPLOYEE_ID, t1.TIMESHEETDAY_ID, t1.DATE_WORKED
FROM (SELECT ROW_NUMBER() OVER(PARTITION BY  EMPLOYEE_ID, TIMESHEETDAY_ID ORDER BY DATE_WORKED) AS RowNumber,
            EMPLOYEE_ID, TIMESHEETDAY_ID, DATE_WORKED
      FROM (SELECT EMPLOYEE_ID, TIMESHEETDAY_ID, DATE_WORKED       
            FROM  TIMESHEET_DAY d
                  INNER JOIN TIMESHEET t ON t.TIMESHEET_ID = d.TIMESHEET_ID
            GROUP BY EMPLOYEE_ID, TIMESHEETDAY_ID, DATE_WORKED
            HAVING SUM(HOURS_WORKED) > 0) t ) t1
     INNER JOIN      
     (SELECT ROW_NUMBER() OVER(PARTITION BY  EMPLOYEE_ID, TIMESHEETDAY_ID ORDER BY DATE_WORKED) AS RowNumber,
            EMPLOYEE_ID, TIMESHEETDAY_ID, DATE_WORKED
      FROM (SELECT EMPLOYEE_ID, TIMESHEETDAY_ID, DATE_WORKED       
            FROM  TIMESHEET_DAY d
                  INNER JOIN TIMESHEET t ON t.TIMESHEET_ID = d.TIMESHEET_ID
            GROUP BY EMPLOYEE_ID, TIMESHEETDAY_ID, DATE_WORKED
            HAVING SUM(HOURS_WORKED) > 0) t ) t2 ON t1.RowNumber = t2.RowNumber + 1
WHERE t2.DATE_WORKED - t1.DATE_WORKED >= 7 
于 2012-01-27T16:11:48.100 回答
0

我会通过计算每个时间表的天数来至少部分使用 SQL 来完成,然后在程序中执行其余的逻辑。这会识别缺少天数的时间表:

SELECT * FROM
    (SELECT s.timesheet_id, SUM(CASE WHEN d.hours_worked > 0 THEN 1 ELSE 0 END) AS days_worked
    FROM
        TimeSheet s
        LEFT JOIN TimeSheet_Day d
            ON s.timesheet_id = d.timesheet_id
    GROUP BY
        s.timesheet_id
    HAVING SUM(CASE WHEN d.hours_worked > 0 THEN 1 ELSE 0 END) < 14) X
    INNER JOIN TimeSheet
        ON TimeSheet.timesheet_id = X.timesheet_id
    LEFT JOIN TimeSheet_Day
        ON TimeSheet.timesheet_id = TimeSheet_Day.timesheet_id
    ORDER BY
        TimeSheet.employee_id, TimeSheet.timesheet_id, TimeSheet_Day.date_worked
于 2012-01-27T15:58:58.820 回答