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
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:
SELECT a.name AS "Name",
SUM(noOfDays = 0) AS "Day 0", SUM(noOfDays = 1) AS "Day 1",
SUM(noOfDays = 2) AS "Day 2", SUM(noOfDays = 3) AS "Day 3",
SUM(noOfDays = 4) AS "Day 4", SUM(noOfDays >= 5) AS "Day 5"
FROM (SELECT a.number, a.name, DATEDIFF(DATE(b.dateEnded), DATE(a.dateStarted)) noOfDays
FROM employee a INNER JOIN project b ON (b.number = a.number and b.dateEnded>a.dateStarted)
) AS a
GROUP BY a.name
Check the SQL FIDDLE DEMO
| 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 |