SUM of column with Left Outer Join

Posted by Matt on Stack Overflow See other posts from Stack Overflow or by Matt
Published on 2012-06-28T15:08:50Z Indexed on 2012/06/28 15:16 UTC
Read the original article Hit count: 195

Filed under:

I am trying to get the Count of all records that have at least on person who is authorized on the record. Basically, a Record can have more than one person associated with it. I want to return the count of Total Records, a count of total Authorized Records where at least 1 person is authorized, and a count of total NotAuthorized records where no person associated with record is authorized. It doesn't matter if one person is authorized per Record or if 3 people are authorized for that record, that should add 1 to the Authorized counter.

The current query is incrementing Auth and Non auth for each person added per record rather, than one per record. If no people are assigned to the record that should also count towards Not Auth.

SELECT Count(DISTINCT Record.RecordID) AS TotalRecords,
SUM(CASE WHEN People.PersonLevel = 1 THEN 1 ELSE 0 END) AS Authorized,
SUM(CASE WHEN People.PersonLevel <> 1 THEN 1 ELSE 0 END) AS NotAuthorized
FROM Record
LEFT OUTER JOIN RecordPeople ON Record.RecordID = RecordPeople.RecordID
LEFT OUTER JOIN People ON RecordPeople.PersonID = People.PersonID

© Stack Overflow or respective owner

Related posts about tsql