0

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
2
  • 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 id Commented Sep 1, 2015 at 16:40
  • you don't need sum(reghours+othours) those values are ALREADY sums, and their values wouldn't be ready until after the row's generated. just reghours+othous as total_hours should do. Commented Sep 1, 2015 at 16:42

1 Answer 1

1
SELECT  TOP (100) PERCENT id, year, SUM(ISNULL(Reghours_worked, 0)) AS RegHours, 
                  SUM(ISNULL(OThours, 0)) AS OThours,  
                  SUM(ISNULL(Reghours_worked, 0)+ ISNULL(OThours, 0)) AS TotalHours_2010
FROM  dbo.hours
WHERE (year = '2010')
GROUP BY id, year
ORDER BY id
Sign up to request clarification or add additional context in comments.

4 Comments

Tip: Good information about COALESCE and ISNULL is at SQL Server Pro here and MSDN Blogs here.
Thank you for sharing this information, I would definitely check that out.
Thanks for the response. Ruchi's answer fixed the issue.
Thanx WinnieBear for trying out the solution, please make it as a answer if it worked for you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.