Basically what I’m trying to do, there are users that have applicable services within a date range (monthly)
I want to be able to show the User’s available time for services (in hours), as well as how many hours they have scheduled based a table that holds appointment data
So I want it to basically look like
user service available scheduled
-----------------------------------------------------------------
User1 Service1 120 7
User1 Service2 40 0
The Scheduled column is calculated by taking the SUM of the Start and End fields in my Appointment table.
Now my problem is that if there are no appointments scheduled, I’m unsure of how to still show the information that I’m wanting above.
The relationship between the tables are the following:
- 1 NOA per User
- Multiple Services per NOA
-
1 FormType per Service
-
Appointment holds FormTypeID as a
FK - ClientAppointment holds the AppointmentID and UserID (the same user with the assigned NOA)
SELECT
--NOA
noa.noaID, noa.userID as 'ClientUserID',
--Service
service.BillingCode + service.MOD1 + service.MOD2 + service.MOD3 + service.MOD4 AS BillingCode, service.FormTypeID, service.StartDate, service.EndDate, service.CurrentUnits, service.Adjustment,
--Scheduler
scheduler.*
FROM LEL_NOA noa
LEFT JOIN LEL_Service service ON service.noaID = noa.noaID
LEFT OUTER JOIN
(
SELECT ca.ClientID, SUM(DATEDIFF(second, a.Start, a.[End]) / 3600) as ScheduledUnits FROM LEL_Scheduler_Appointment a
LEFT JOIN LEL_Scheduler_ClientAppointment ca ON a.ApptID = ca.ApptID
WHERE a.Start BETWEEN '1/1/2012' and '1/31/2012'
AND a.[End] BETWEEN '1/1/2012' and '1/31/2012'
GROUP BY ca.ClientID
) AS scheduler ON noa.UserID = scheduler.ClientID
WHERE noa.UserID = 4
AND service.StartDate BETWEEN '1/1/2012' and '1/31/2012'
AND service.EndDate BETWEEN '1/1/2012' and '1/31/2012'
ORDER BY 'ClientUserID', BillingCode, FormTypeID, StartDate
The above procedure will pull back for the month, 21 availabl, 7 scheduled, but the person with a UserID = 4 has another service for that time period and I would like to show the information with 0 hours scheduled as the next item in my table.
(noaID, ClientUserID, BillingCode, FormTypeID, StartDate, EndDate, CurrentUnits, Adjustment, ScheduledUnits) VALUES
(203, 25, 'x888', 6, '4/16/2012 4:24:19 PM', '4/16/2012 4:24:19 PM', 0, 0, 5.000000),
(203, 25, 'x999', 1, '4/1/2012 12:00:00 AM', '4/30/2012 12:00:00 AM', 10, 0, 5.000000)
The problem is that the first entry, there aren’t any appointments scheduled but yet it’s still showing 5 (which the second sum is correct)
Try reworking your query to use an inline sub-query. Performance might suffer, but it will be easier to get a correct query.