maybe someone could shed some light on the statement that I have been battling with the entire day 🙂
I have 3 tables
Holiday
holidayID | userID | dateFrom | dateTo
1 | 1 | 2012-01-01 | 2012-01-01
2 | 1 | 2012-01-15 | 2012-01-20
Status
statusID | holidayID | statusText
1 | 1 | accepted
2 | 2 | declined
UserSettings
id | userID | HolidaysAllowed
1 | 1 | 20
What I am trying to do is get the following result
Result
HolidaysAllowed | HolidaysLeft (Allowed - Taken) | HolidaysTaken (Sum of Holidays)
20 | 19 | 1
I am able to get all three columns if I dont state a status – here is the closest I got
SELECT
IFNULL(SUM( IF( h.dateTo = h.dateFrom, 1, DATEDIFF( h.dateTo, h.dateFrom ) ) ), 0) AS holidaysTaken,
IFNULL(us.HolidaysAllowed - ( SUM( IF( h.DateTo = h.DateFrom, 1, DATEDIFF( h.DateTo, h.dateFrom ) ) ) ), 0) AS holidaysLeftover,
us.HolidaysAllowed
FROM userSettings us
LEFT JOIN holiday h
ON h.userID = 1
JOIN status s
ON s.holidayID = h.holidayID AND s.statusID = 1
WHERE
us.userID = 1
GROUP BY h.userID;
The main problem is that if there is no holiday with statusID = 2 then result column 1 & 2 are 0 (which is correct) but column 3 (HolidaysAllowed) is NULL (incorrect as it needs to always return the value from the table UserSettings). The above query only returns a correct response when there is at least 1 record (holiday) with the correct status… what am I doing wrong? 🙂
Its just driving me nuts 🙂 Thanks in advance for any help! Much appreciated!
UPDATE
Thanks to everyone who commented… the expected result is as follows
Get all holidays that have a status = 1 (i.e accepted) then calculate the holidays statistics against that of the holidays allowed. I.e.
20 days in total, 1 holiday accepted = 19 days left to take
thanks again
1 Answer