0

So, I'm wondering if it's possible to count how many times a variable appears in table using SQL.

Example table:

ID   TextColumn 
1    foo  
2    foo foo foo
3    bar   

$var = "foo";

Return all columns with $var and count of $var order by highest to lowest.

Example result:

(1)ID=2,count=3 (2)ID=1,count=1

Is this possible to do using only SQL?

I asked a similiar question earlier but it wasn't clear, so if this one is also unclear please let me know.

3
  • 1
    you have tagged both mysql and sql-server... which is solution you actually need or both. Commented Jan 20, 2016 at 6:48
  • And again today: en.wikipedia.org/wiki/Database_normalization Commented Jan 20, 2016 at 6:48
  • @dean sorry, only meant to tag mysql Commented Jan 20, 2016 at 8:59

1 Answer 1

1

If you're using SQL Server, you can do this using LEN and REPLACE:

DECLARE @var VARCHAR(MAX) = 'foo'

SELECT *, 
    (LEN(TextColumn) - LEN(REPLACE(TextColumn, @var, ''))) / LEN(@var)
FROM tbl
WHERE 
    CHARINDEX(@var, TextColumn) > 0
ORDER BY 
    (LEN(TextColumn) - LEN(REPLACE(TextColumn, @var, ''))) / LEN(@var) DESC

SQL Fiddle

Sign up to request clarification or add additional context in comments.

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.