1

I have a table with 5 columns (primary_key, abstractid, sentid, wordid, term).

This query pulls up a list of distinct terms that appear in less than 6 distinct abstractid's.

SELECT 
    term, COUNT(distinct abstractid) AS "num" 
FROM 
    nsfabstracts 
HAVING 
   COUNT(distinct abstractid) < 6 
GROUP BY 
   term 
ORDER BY 
   "num" DESC;

How would I modify the above query to count the number of rows it returns instead? Also, how would I delete all rows associated with the above query?

3
  • 2
    Please tag your question with the database you are using. Commented Mar 4, 2015 at 3:15
  • How can you have HAVING before GROUP BY? Commented Mar 4, 2015 at 3:43
  • I'm not sure. using the query I listed above I appear to get the expected results. I'll try reordering and see if I get the same results. I added a tag for oracle-sqldeveloper. Commented Mar 4, 2015 at 14:10

1 Answer 1

5

Be lazy, use a sub-select:

SELECT count(*) FROM (
     SELECT term, COUNT(distinct abstractid) AS "num" FROM nsfabstracts HAVING COUNT(distinct abstractid) < 6 GROUP BY term
)

and

DELETE FROM nsfabstracts WHERE term in (
     SELECT term, COUNT(distinct abstractid) AS "num" FROM nsfabstracts HAVING COUNT(distinct abstractid) < 6 GROUP BY term
)
Sign up to request clarification or add additional context in comments.

1 Comment

This actually isn't lazy in my opinion, and you have the benefit of running the sub-select to verify the rows which will be deleted before actually doing so (if running the command interactively).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.