我使用的是sqlite,我的查询几乎可以使用。但是,week_hours的计算并不能产生正确的数字。我试图计算我的员工在特定日期范围内为特定客户花费了多少小时。小时数存储在timesheet_line文件中的1个记录中的单独字段(mon,tues,wed,thurs,fri,sat,sun)中。当然,可能有超过1条记录与该customerID相关联,因此我使用Sum来计算总数。如果我不在每周小时使用Sum,并且在timesheet_line文件中只有1条记录,则计算将返回正确的值。 labour_rate计算也算错误。这是一个奇怪的,因为我需要计算每周花费的时间并将其乘以为客户工作的员工的cost_rate。每个员工可能有不同的费用。
SELECT c.customerID, c.customer, sum(il.line_price) AS net, sum (tl.mon + tl.tues + tl.wed + tl.thurs + tl.fri + tl.sat + tl.sun) AS weekly_hours,
sum( (tl.mon + tl.tues + tl.wed + tl.thurs + tl.fri + tl.sat + tl.sun) * s.cost_rate ) AS labour_rate
FROM customer AS c
LEFT JOIN invoice AS i
ON c.customerID = i.customerID
LEFT JOIN invoice_line AS il
ON i.invoiceID = il.invoiceID
LEFT JOIN timesheet_line AS tl
ON c.customerID = tl.customerID
LEFT JOIN timesheet AS t
ON tl.timesheetID = t.timesheetID
LEFT JOIN staff AS s
ON t.staffID = s.staffID
LEFT JOIN project AS p
ON tl.projectID = p.projectID
WHERE (i.date BETWEEN '2015-03-01' AND '2015-12-01') OR
(tl.customerID = c.customerID AND t.date BETWEEN '2015-03-01' AND '2015-12-01')
GROUP BY c.customerID
ORDER BY c.customer ASC