6

I have the following simple query,

SELECT US_LOGON_NAME as Username, 
COUNT(I.IS_ISSUE_NO) as Issues
FROM ISSUES I JOIN USERS U ON I.IS_ASSIGNED_USER_ID = U.US_USER_ID
WHERE I.IS_RECEIVED_DATETIME BETWEEN 20110101000000 AND 20110107000000
GROUP BY U.US_LOGON_NAME; 

Where I want to add additional COUNT() functions to the select list but impose certain where conditions on them. Is this done with a CASE() statement somehow? I tried putting Where clauses inside the select list, and that doesn't seem to be allowed. I'm not sure if subqueries are really necessary here, but I dont think so.

For example I want one COUNT() function that only counts issues within a certain range, then another in another range or with other assorted conditions, etc:

 SELECT US_LOGON_NAME as Username, 
 COUNT(I.IS_ISSUE_NO (condition here)
 COUNT(I.IS_ISSUE_NO (a different condition here)

etc...

Still grouped by Logon Name.

Thanks.

Sean
  • 769
  • 2
  • 8
  • 7

3 Answers3

11
SELECT
  SUM(CASE WHEN I.IS_ISSUE_NO (condition here) THEN 1 ELSE 0 END) AS COND1
  SUM(CASE WHEN I.IS_ISSUE_NO (condition here) THEN 1 ELSE 0 END) AS COND2
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
5

A couple of solutions.

You can take advantage of the fact that SQL does not COUNT NULL values:

  SELECT US_LOGON_NAME as Username, 
  COUNT(CASE WHEN <cond>       THEN I.IS_ISSUE_NO ELSE NULL END)
  COUNT(CASE WHEN <other cond> THEN I.IS_ISSUE_NO ELSE NULL END)
  . . .

Or you can use SUM instead of COUNT:

  SELECT US_LOGON_NAME as Username, 
  SUM(CASE WHEN <cond>       THEN 1 ELSE 0 END)
  SUM(CASE WHEN <other cond> THEN 1 ELSE 0 END)
  . . .

In either case, you can repeat as many times as you need to.

Larry Lustig
  • 49,320
  • 14
  • 110
  • 160
0

The example returns count per user, per IssueType.

;
with
q_00 as (
select
      is_issue_no
    , is_assigned_user_id 
    , case
          when is_issue_no between  1 and 10 then 'A'
          when is_issue_no between 11 and 14 then 'B'
          else  'C'  
      end as IssueType
from Issues 
)
select
      us_logon_name
    , IssueType
    , count(1) as cnt
from q_00  as a
join users as u on a.is_assigned_user_id = u.us_user_id
group by us_logon_name, IssueType
order by us_logon_name, IssueType ;

SQL server 2005 +

Damir Sudarevic
  • 21,891
  • 3
  • 47
  • 71