views:

26

answers:

2

I've been stuck for quite a while now trying to get this query to work. Here's the setup:

I have a [Notes] table that contains a nonunique (Number) column and a nonunique (Result) column. I'm looking to create a SELECT statement that will display each distinct (Number) value where the count of the {(Number), (Result)} tuple where Result = 'NA' is > 25.

Number | Result  
 100   |  'NA'  
 100   |  'TT'  
 101   |  'NA'  
 102   |  'AM'  
 100   |  'TT'  
 200   |  'NA'  
 200   |  'NA'  
 201   |  'NA'

Basically, have an autodialer that calls a number and returns a code depending on the results of the call. We want to ignore numbers that have had an 'NA'(no answer) code returned more than 25 times.

My basic attempts so far have been similar to:

SELECT DISTINCT n1.Number 
FROM Notes n1 
WHERE (SELECT COUNT(*) FROM Notes n2
       WHERE n1.Number = n2.Number and n1.Result = 'NA') > 25

I know this query isn't correct, but in general I'm not sure how to relate the DISTINCT n1.Number from the initial select to the Number used in the subquery COUNT. Most examples I see aren't actually doing this by adding a condition to the COUNT returned. I haven't had to touch too much SQL in the past half decade, so I'm quite rusty.

+3  A: 

Hello,

you can do it like this :

SELECT Number
FROM Notes 
WHERE Result = 'NA'
GROUP BY Number
HAVING COUNT(Result) > 25
Arnaud F.
+ 1 for having but you forgot the WHERE
Conrad Frix
Thanks, that worked perfectly. Just one of those cases where I got locked into trying to do one thing and couldn't see past it.
Joe
@Arnauld since it was accepted I added the WHERE keyword for you in case someone copied and pasted it
Conrad Frix
Hum, sorry for the missing WHERE and thanks to have added it :)
Arnaud F.
+1  A: 

Try this:

SELECT Number
FROM (
    SELECT Number, Count(Result) as CountNA 
    FROM Notes
    WHERE Result = 'NA'
    GROUP BY Number
)
WHERE CountNA > 25

EDIT: depending on SQL product, you may need to give the derived table a table correlation name e.g.

SELECT DT1.Number
  FROM (
        SELECT Number, Count(Result) as CountNA 
          FROM Notes
         WHERE Result = 'NA'
         GROUP 
            BY Number
       ) AS DT1 (Number, CountNA)
 WHERE DT1.CountNA > 25;
Andrew Cooper
It's not recognizing the CountNA in the second where clause. I'm assuming that's because the scope is just within that subquery?
Joe
@onedaywhen Thanks for that
Andrew Cooper