I am trying to SUM work hours for the year 2010 for employees using the following script. Some employees may have multiple lines in the table for the same year. Although a field will populate with 0 if there are no hours, the total result may indicate NULL. I am using a SQL Standard 2005. Suggestions would be appreciated.
SELECT TOP (100) PERCENT id, year, SUM(ISNULL(Reghours_worked, 0)) AS RegHours, SUM(ISNULL(OThours, 0))
OThours, SUM(RegHours + OThours) AS TotalHours_2010
FROM dbo.hours
WHERE (year = '2010')
GROUP BY id, year
ORDER BY id
``
Results below:
id Year RegHours OTHours Total Hours
658261 2010 1449 0 1449
752466 2010 1743 0 1743
144444 2010 1750 0 1750
652152 2010 1142 0 NULL
926541 2010 0 0 0
SELECT TOP (100) PERCENT id, year, SUM(ISNULL(Reghours_worked, 0)) AS RegHours, SUM(ISNULL(OThours, 0)) OThours, SUM(ISNULL(RegHours,0) + ISNULL(OThours,0)) AS TotalHours_2010 FROM dbo.hours WHERE (year = '2010') GROUP BY id, year Order BY idsum(reghours+othours)those values are ALREADY sums, and their values wouldn't be ready until after the row's generated. justreghours+othous as total_hoursshould do.