Friday, March 9, 2012

Multiple COUNTs with different qualifiers in a single query, grouped on another field?

Hi. I was wondering if this could be done simply...

I have a table of daily work shift data that contains an ID for the worker and also a status field that indicates whether the worker logged in correctly. I want to develop a query that for a given period (say, a month) counts the number of total shifts for that worker and the number of those shifts that are incorrectly logged. So, an example result set would be:

worker ID total shifts incorrect shifts

90012 27 6

90036 28 2

Getting either count grouped on the worker ID is easy, getting them both in the same overall select statement is driving me crazy. I'm betting that there is some slick way to do this, but my newbie T-SQL status prevents me from seeing it. Can anyone help?

Thank you!!!

try this

select t.WorkerID,(select Count(WorkerID) from Tablename where [date] between @.fromdate and @.todate and WorkerID=t.WorkerID) [TotalShifts],(select Count(WorkerID) from Tablename where [date] between @.fromdate and @.todate and WorkerID=t.WorkerID and loginstatus = @.status ) [IncorrectShifts] from Tablename t group by t.WorkerID

regards

|||I love the Internet! Thank you!! You even wrote the code for me. I am very grateful! All the best!

No comments:

Post a Comment