I am working on a query to get monthly attendance totals by department. i.e it will show present employees in each department based on attendance logs table where check_type = 'C-IN'
- Table 1:
checkin_out_log
- Columns:
emp_id
,check_time
,check_type
(C-IN, C-OUT)
- Columns:
- Table 2:
department
- Table 3:
employee
Expected output is
Department | Total Staff | Date 1 | Date 2 | Date 3|......
finance | 60 | 50 | 55 | 48 |.....
Here is my query which is currently returning me total staff in each department,
SELECT
*
FROM
(SELECT
d.id, d.name AS Department, T.DateToCheck,
COUNT(e.id) AS staff
FROM
employee e
CROSS JOIN
(SELECT
CAST(DATEADD(DAY, number, @DateFrom) AS DATE)
FROM
master..spt_values
WHERE
type = 'P'
AND DATEADD(DAY, number, @DateFrom) <= @DateTo ) T (DateToCheck)
LEFT JOIN
department d ON d.id = e.department
WHERE
d.id = 7
GROUP BY
d.id, d.name, T.DateToCheck) T
PIVOT
(MAX(staff)
FOR DateToCheck IN ([2018-09-01],[2018-09-02],[2018-09-03],[2018-09-04],[2018-09-05],[2018-09-06],[2018-09-07],[2018-09-08],[2018-09-09],[2018-09-10],
[2018-09-11],[2018-09-12],[2018-09-13],[2018-09-14],[2018-09-15],[2018-09-16],[2018-09-17],[2018-09-18],[2018-09-19],[2018-09-20],[2018-09-21],[2018-09-22],[2018-09-23],
[2018-09-24],[2018-09-25],[2018-09-26],[2018-09-27],[2018-09-28],[2018-09-29],[2018-09-30])) P
;