views:

23

answers:

2

Hi

I am trying to create a report and am looking to pull out some information from a table 'contact'. I am trying to pull out the 'advisor' relating to the contact and a count of contacts who have that advisor based on a set of criteria. This is fine and works, however, I want to pull out a third column which is also a 'Count' based on a different set of criteria. This is where I am having trouble.

Currently I have the below which states 'unable to parse query text':

SELECT  advisoridName AS Advisor,
  COUNT(*) WHERE (advisorid IS NOT NULL) AND (ContactType = 1) AND (StateCode = 0) AS 'Active Participants',
  COUNT(*) WHERE (advisorid IS NOT NULL) AND (ContactType = 1) AS 'Total Participants'
FROM Contact
GROUP BY  advisoridName, advisorid
ORDER BY  PDA

It would be appreciated if you could steer me in the right direction.

Thanks in advance

+1  A: 

COUNT(*) isn't conditional, at least not in TSQL. I suggest using SUM(CASE WHEN... - like so:

SELECT  advisoridName AS Advisor,
  SUM(CASE WHEN (advisorid IS NOT NULL) AND (ContactType = 1) AND (StateCode = 0) 
           THEN 1
           ELSE 0
      END) AS 'Active Participants',
  SUM(CASE WHEN (advisorid IS NOT NULL) AND (ContactType = 1) 
           THEN 1
           ELSE 0
      END) AS 'Total Participants'
FROM Contact
GROUP BY  advisoridName, advisorid
ORDER BY  PDA
Mark Bannister
A: 

You can do the same thing with COUNT as you did with but you dont need a GROUP BY

SELECT COUNT (CASE when advisorid IS NOT NULL AND ContactType = 1 AND StateCode = 0 THEN AdvisorID END ) as ActiveParticipants,
COUNT (CASE when advisorid IS NOT NULL AND ContactType = 1 THEN AdvisorID) as TotalParticipants
FROM Contact
ORDER By PDA
D.S.