0

Using Oracle SQL, I have a column of strings called "title" in a table called OBJECT. Words are separated by spaces.

I want to write a query count how many titles have the same first word as other titles in the table. I want to output the word, and a count of how many entries begin with that word as FIRSTWORD, WORD_COUNT. E.G.

FIRSTWORD     WORD_COUNT
Word1   23
Word2   15

I am using both SUBSTR and INSTR to get the first word of each entry, and regexp_count to try and count the number of times it appears. So far, I can get it to output a list of the first words, but my count is always 0:

SELECT 
(SUBSTR(title, 0, INSTR(title, ' ')-1)) AS FIRSTWORD, 
(REGEXP_COUNT(title, INSTR(title, ' ')-1)) AS WORD COUNT 
FROM OBJECT GROUP BY title;

2 Answers 2

4

A subquery should do the trick.

WITH firstwords AS (
  SELECT (SUBSTR(OBJECT.title, 0, INSTR(OBJECT.title, ' ')-1)) AS WORD
  FROM OBJECT)
SELECT word, count(word)
FROM firstwords
GROUP BY word;
Sign up to request clarification or add additional context in comments.

1 Comment

Thankyou! That was perfect. I didn't know how to do this properly.
2

FYI. You don't actually need a subquery. You can do the calculation at one level:

select SUBSTR(OBJECT.title, 0, INSTR(OBJECT.title, ' ')-1)) AS WORD, count(*)
from OBJECT
group by SUBSTR(OBJECT.title, 0, INSTR(OBJECT.title, ' ')-1)) ;

Comments

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.