Im trying to write a MySQL statement that will bring me back these results:
## Name | Day 0 | Day 1 | Day 2 | Day 3 | Day 4 | Day 5 |
##Jeff | 0 | 3 | 1 | 2 | 1 | 1 |
##Larry | 1 | 1 | 4 | 4 | 1 | 0 |
Based on how many tasks each employee performed on each day.
My database tables are as follows:
Employee
id
(INT), number
(VARCHAR), name
(VARCHAR), dateStarted
(VARCHAR),
Project
id
(INT), number
(VARCHAR), dateEnded
(DATETIME)
Right now I'm using this statement:
SELECT
a.name AS "Name",
count(abs(datediff(STR_TO_DATE(a.dateStarted, '%Y-%m-%d %H:%i:%s'), b.dateEnded))) AS "Day 0",
count(abs(datediff(STR_TO_DATE(a.dateStarted, '%Y-%m-%d %H:%i:%s'), b.dateEnded))) AS "Day 1",
count(abs(datediff(STR_TO_DATE(a.dateStarted, '%Y-%m-%d %H:%i:%s'), b.dateEnded))) AS "Day 2",
count(abs(datediff(STR_TO_DATE(a.dateStarted, '%Y-%m-%d %H:%i:%s'), b.dateEnded))) AS "Day 3",
count(abs(datediff(STR_TO_DATE(a.dateStarted, '%Y-%m-%d %H:%i:%s'), b.dateEnded))) AS "Day 4",
count(abs(datediff(STR_TO_DATE(a.dateStarted, '%Y-%m-%d %H:%i:%s'), b.dateEnded))) AS "Day 5"
FROM employee a, project b
WHERE b.number=a.number
AND "Day 0" = 0
AND "Day 1" = 1
AND "Day 2" = 2
AND "Day 3" = 3
AND "Day 4" = 4
AND "Day 5" >= 5
Current Output
The above statement works but for some reason it does not provide the desired result mentioned in the requirement above. Any ideas on how I can fix/change it?
edit
If I take out:
AND "Day 0" = 0
AND "Day 1" = 1
AND "Day 2" = 2
AND "Day 3" = 3
AND "Day 4" = 4
AND "Day 5" >= 5
Then it prints out:
## Name | Day 0 | Day 1 | Day 2 | Day 3 | Day 4 | Day 5 |
##Jeff | 9 | 9 | 9 | 9 | 9 | 9 |
The previous solution could be improved by doing the following join statement or where..
Make sure to have an index ( unique ? ) on project (number,dateEnded) You could also try to add index on employee (number, dateStarted)
NULL values are usually not part of any indexes (as they are null), you could try updating the default value of that field to '0000-00-00', this way it would get indexed and potentially add speed.
Try this:
Check the SQL FIDDLE DEMO
Using the SQL fiddle data from one of the previous answers, I have tried this:-
Seems to give the right results and be quite fast.
SQL fiddle here:-
http://www.sqlfiddle.com/#!2/db498/84
Bit more efficient (but doesn't cope with employees who have no projects):-
SQL fiddle here:-
http://www.sqlfiddle.com/#!2/db498/89
Try this:
Check the SQL FIDDLE DEMO
Try this:
See SQL Fiddle Demo (- have made some assumptions on your data based on the info provided).