Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi,I have the following table structure:tbl_Subject > one-to-many > tbl_Group > one-to-many > tbl_ItemI would like to know if the following is possible:tbl_Subject------------subjID empID ... other1 2362 2363 5424 725 tbl_Group------------grpID subjID ... other10 120 110 210 310 4tbl_Item-------------itemID grpID subjID isFailed ... other1 10 1 12 10 1 03 20 1 04 10 2 05 10 2 06 10 3 17 10 3 16 10 4 08 10 4 0 The result that I am trying to get would look like thisempID countFailed countPassed236 1 1542 1 0725 0 1So, I want to count one failed if any of the items have a failed value for in the item table, (not all of the failed items).I am running MS-SQL 2008r2.Thanks for any help.
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts
Posted - 2012-07-24 : 20:49:02
Would this give you the results you are looking for?
SELECT s.empId, SUM(DISTINCT CASE WHEN i.isFailed = 1 THEN 1 ELSE 0 END), SUM(DISTINCT CASE WHEN i.isFailed = 0 THEN 1 ELSE 0 END)FROM tbl_Subject s INNER JOIN tbl_Group g ON g.subjId = s.subjId INNER JOIN tbl_Item i ON i.grpId = g.grpId AND i.subjId = g.subjIdGROUP BY s.empId
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2012-07-24 : 22:59:44
[code]SELECT s.empID,SUM(CASE WHEN Failed = 1 THEN 1 ELSE 0 END) AS CountFailed,SUM(CASE WHEN Failed = 0 THEN 1 ELSE 0 END) AS CountPassedFROM tbl_Subject sINNER JOIN (SELECT subjID, CASE WHEN SUM(CASE WHEN isFailed =1 THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END AS Failed FROM tbl_Item i INNER JOIN tbl_Group g ON i.grpID = g.grpID AND i.subjID = g.subjID GROUP BY subjID )iON i.subjID = s.subjIDGROUP BY s.empID [/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/
mauisys
Starting Member
7 Posts
Posted - 2012-07-25 : 12:09:19
Thanks so much visakh16. This is exactly what I needed!
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2012-07-25 : 12:13:09
welcome ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/