因此,我将数据以以下格式导入到表中(让我们称之为RAWDATA):
EMPID | STARTDATE | ENDDATE | TOTALHOURS | TOTALWAGES ABC123 | 01-01-2013 | 01-28-2013 | 160.0 | 1800.00 XYZ987 | 01-01-2013 | 01-31-2013 | 200.0 | 2500.00
我需要获取这些数据,并以以下格式将其放入另一个表(EMPDATA)中:
EMPID | DATE | HOURS | WAGES ABC123 | 01-01-2013 | 5.71 | 64.29 ABC123 | 01-02-2013 | 5.71 | 64.29 ABC123 | 01-03-2013 | 5.71 | 64.29 ...... | .......... | .... | ..... XYZ987 | 01-01-2013 | 6.45 | 80.66 XYZ987 | 01-02-2013 | 6.45 | 80.66 XYZ987 | 01-03-2013 | 6.45 | 80.66 ...... | .......... | .... | .....
我的想法是在STARTDATE和ENDDATE之间执行DATEDIFF,以计算多少天(在本例中为28天)来分配小时和工资,然后每天插入一行,其中包含每天的平均小时和工资。所有这些都将通过RAWDATA表上的触发器来完成。我只是不确定如何在触发器中从STARTDATE迭代到ENDDATE。
编辑:我还应该指出,导入的数据并不总是每一行都有相同的开始/结束日期。我已经更新了第一个表示例来表明这一点。
date
JOIN
startdate
enddate
totalhours
totalwages
这是我的解决方案:
SELECT a.empid, b.dd AS date, CAST(a.totalhours AS decimal) / (DATEDIFF(day, startdate, enddate) + 1) AS hours, CAST(a.totalwages AS decimal) / (DATEDIFF(day, startdate, enddate) + 1) AS wages FROM wages a INNER JOIN dates b ON dd BETWEEN a.startdate AND a.enddate
结果
| EMPID | DATE | HOURS | WAGES | -------------------------------------------------------- | ABC123 | 2013-01-01 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-02 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-03 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-04 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-05 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-06 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-07 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-08 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-09 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-10 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-11 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-12 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-13 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-14 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-15 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-16 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-17 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-18 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-19 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-20 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-21 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-22 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-23 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-24 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-25 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-26 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-27 | 5.71428571428 | 64.28571428571 | | ABC123 | 2013-01-28 | 5.71428571428 | 64.28571428571 |
sqlfiddle