I’m looking to compute a column based on two other columns, but I have some special cases where the computation has to take multiple rows into account.
Here’s the query as it stands now:
SELECT
UserName
, EntryDate
, Project
, HoursWorked
, HoursAvailable
, UtilPct as HoursWorked / HoursAvailable
FROM
MyDatabase
ORDER BY
EntryDate
Which results in:
UserName EntryDate Project HoursWorked HoursAvailable UtilPct
Justin 12/17/2012 ABC 8 8 100
Justin 12/18/2012 ABC 4 8 50
Justin 12/18/2012 DEF 4 8 50
But 50% utilization for the last two entries is wrong, because both happened on the same day. Both of those rows should show 100%.
I need the query to…
- Sum up all of the HoursWorked for a certain day
- Divide that by the max HoursAvailable for that day
- Put that value into the UtilPct column for each row
How do I make it do that?
Sum up all of the HoursWorked:
Divide that by the max HoursAvailable for that day
Put that value into the UtilPct column for each row:
But now you won’t be able to divide the rows by
Project, you will only see the time utilization any single day. If you try toGROUP BYProject, you will get 50% instead of 100% again.That is because you are asking for 4/8 to be 100%, and that would get you semantically nonsensical answers, such as “On Tuesday, I worked 100% on project ABC, and also 100% on project DEF”, to which one could answer “So on Tuesdays there’s 200% of you?”
You can solve the quandary using a
JOINbetween the table and itself to get theTotalHoursWorkedin a single day, which is semantically different from the HoursWorked on a single project:Now the UtilPct will refer to the time usage of that day, which means you could get a 100% value on a project even if you worked at it for five minutes only, provided those five minutes were all that you had available that day. And you will still be able to add another column to indicate the percentage of
HoursWorkedoverHoursAvailablefor that project that day (in most systems, it ought to be roughly proportional to that project’s priority).