Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 每天输入超过24小时时拆分或复制记录_Sql_Sql Server_Stored Procedures - Fatal编程技术网

Sql 每天输入超过24小时时拆分或复制记录

Sql 每天输入超过24小时时拆分或复制记录,sql,sql-server,stored-procedures,Sql,Sql Server,Stored Procedures,我们有一个缺勤系统,人们把他们的总休假时间放进去,而不是分成不同的记录。我的数据是这样的 EMP_ID | HOURS | DATE ---------|-----------|------------ 1 | 24 | 2013-10-10 2 | 8 | 2013-11-06 3 | 48 | 2013-11-13 4 | 51 | 2013-1

我们有一个缺勤系统,人们把他们的总休假时间放进去,而不是分成不同的记录。我的数据是这样的

EMP_ID   |   HOURS   |   DATE  
---------|-----------|------------   
1        |    24     |  2013-10-10
2        |     8     |  2013-11-06
3        |    48     |  2013-11-13
4        |    51     |  2013-12-10
我需要一个查询(这最终可能是一个存储过程),它将像这样返回数据

    EMP_ID   |   HOURS   |   DATE
-------------|-----------|-------------
    1        |    24     |  2013-10-10
    2        |     8     |  2013-11-06
    3        |    24     |  2013-11-13
    3        |    24     |  2013-11-14
    4        |    24     |  2013-12-10
    4        |    24     |  2013-12-11
    4        |     3     |  2013-12-12
请注意一天是如何增加1的。任何输入超过24小时的人都将被拆分记录。任何剩余的部分都会在最后作为部分日加上


最后(我可以自己处理),我需要小心不要跨越年底。

如果这是SQL Server,可以使用递归CTE

with cte as
(
  select emp_id, 
    hours as tHours, 
    case when hours >= 24 then 24 else hours end as hours, 
    date 
  from YourTable

  UNION ALL

  select c.emp_id, 
    c.thours - (case when c.thours >= 24 then 24 else c.hours end),
    case when (c.thours - (case when c.thours >= 24 then 24 else c.hours end)) >= 24 then 24 else c.thours - 24 end, 
    dateadd(day, 1, c.date)
  from cte c
  join YourTable m on c.thours - 24 > 0 and m.emp_id = c.emp_id
)

select emp_id, 
  hours, 
  date 
from cte
order by emp_id, date

是的,我应该补充一点,这是SQL Server。谢谢你的回答。事实上,我最终选择了另一个方向来解决这个问题。一旦我把代码清理干净,我会把我的答案发布给后代。顺便说一下,你的看起来更干净(但我还没有测试过)