有幾個視圖可以完成這項工作:一個用於工作時間,一個用於員工,然後您可以加入他們並設置過濾器,如這樣的:
-- Query the working hours
CREATE VIEW
vw_working_hours
AS
SELECT
employee_id,
year,
month,
SUM((timeout+12) - timein) AS total_working_hours
FROM
timesheets
GROUP BY
employee_id,
year,
month;
-- Query the employees
CREATE VIEW
vw_employees
AS
SELECT
DISTINCT
employee_id,
employee_name,
department
FROM
timesheets;
-- This query is the actual report
-- just had to filter by department
-- in your script
SELECT
wh.employee_id,
emp.employee_name,
wh.total_working_hours
FROM
vw_working_hours AS wh
JOIN
vw_employees AS emp
ON
wh.employee_id = emp.employee_id
WHERE
wh.year = 2016
AND
wh.month = '09'
AND
emp.department = 'finance';
或者,在一個單一的查詢(無意見):
SELECT
wh.employee_id,
emp.employee_name,
wh.total_working_hours
FROM
(
SELECT
employee_id,
year,
month,
SUM((timeout+12) - timein) AS total_working_hours
FROM
timesheets
GROUP BY
employee_id,
year,
month
) AS wh
JOIN
(
SELECT
DISTINCT
employee_id,
employee_name,
department
FROM
timesheets
) AS emp
ON
wh.employee_id = emp.employee_id
WHERE
wh.year = 2016
AND
wh.month = '09'
AND
emp.department = 'finance';
在PHP中,你應該使用一個循環和積累的變量。首先,你應該預過濾器這樣的查詢:
SELECT
*
FROM
timesheets
WHERE
department = 'finance'
AND
year = 2016
AND
month = '09'
ORDER BY
employee_id;
然後,如果結果是在一個名爲$行,東西在PHP這樣的多維數組:
$employee_id = $rows[0]['employee_id'];
$employee_name = $rows[0]['employee_name'];
$accumulated = 0;
foreach($rows as $row) {
$total_working_hours = ($row['timeout'] + 12) - $row['timein'];
if ($row['employee_id'] == $employee_id) {
// Same employee, acumulate
$accumulated += $total_working_hours;
} else {
// Another employee, pass the acumulation to result
$rowTmp['employee_id'] = $employee_id;
$rowTmp['employee_name'] = $employee_name;
$rowTmp['total_working_hours'] = $accumulated;
$result[] = $rowTmp;
// Updated the accumulation variables
// new employee
$employee_id = $row['employee_id'];
$employee_name = $row['employee_name'];
// reset accumulated
$accumulated = $total_working_hours;
}
}
// at the end, updates the las result:
$rowTmp['employee_id'] = $employee_id;
$rowTmp['employee_name'] = $employee_name;
$rowTmp['total_working_hours'] = $accumulated;
$result[] = $rowTmp;
// Should pass result to HTML table
print_r($result);
你爲什麼不使用任何數據庫? –
我的意思是,你使用數據庫系統來存儲和獲取你的數據? –
是的,我使用MYSQL – the7k