Question

Basically, I want to know the SQL Equivalent of Excel's COUNTIF(Range,Criteria)

I want this Output

CALL ID |  Name  | Phone Number | # of Occurrences    
  0001  | Name1  |  0000000000  |        2    
  0002  | Name2  |  1111111111  |        1    
  0003  | Name1  |  0000000000  |        2    
  0004  | Name3  |  2222222222  |        2    
  0005  | Name5  |  4444444444  |        1    
  0006  | Name4  |  3333333333  |        1    
  0007  | Name3  |  2222222222  |        2

NOT This Output

CALL ID |  Name  | Phone Number | # of Occurrences    
  0001  | Name1  |  0000000000  |        2    
  0002  | Name2  |  1111111111  |        1    
  0004  | Name3  |  2222222222  |        2    
  0005  | Name5  |  4444444444  |        1    
  0006  | Name4  |  3333333333  |        1    

This is a simplified table. This is my complex table and this is the result Result

What i wanted is to avoid having 2 Appointments, instead, list them in separate rows so that the appointment is only 1

Here is the query

SELECT
a."Call ID" as "Call ID",
CONCAT(a.Campaign, '-', a."CONTACT ID") as IDENTIFIER,
REPLACE(a."Campaign",'CW-','') as "Campaign",
a."DNIS" as "DNIS",
a."CONTACT ID" as "CONTACT ID",
a."first_name" as "first_name",
a."last_name" as "last_name",
a."city" as "city",
a."street" as "street",
a."zip" as "zip",
a."state" as "state",
a."number2" as "number2",
a."number1" as "number1",
a."Customer ID - real" as "Customer ID - real",
COUNT(a."Call ID") as "Dial Attempts"
FROM  "Five9 Calls" a 
group by 
CONCAT(a.Campaign, '-', a."CONTACT ID"),
REPLACE(a."Campaign",'CW-',''),
a."CONTACT ID",
a."first_name",
a."last_name",
a."city",
a."street",
a."zip",
a."state",
a."number2",
a."number1"
Was it helpful?

Solution

Declan's answer gives you the number of names linked to each phone number (one row per phone number).

If it's important for you to keep the same number of row (i.e. the same layout you've described in your question), you can use an OVER clause.

SELECT NAME, [PHONE NUMBER], COUNT(NAME) OVER (PARTITION BY [PHONE NUMBER]) AS OCCUR
FROM YOURTABLE

With OVER there's no need for a GROUP BY.

OTHER TIPS

If you need a count of the occurance of each phone number, which is what I can glean from your data, you would use the following.

SELECT [PHONE NUMBER],COUNT(NAME) AS OCCUR
FROM YOURTABLE
GROUP BY [PHONE NUMBER]
select call_id, name, phone_number, count() over (partition by name, phone_id order by name asc, phone_id asc) occur
From yourtable
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top