How to count instances of character in SQL Column
In SQL Server:
SELECT LEN(REPLACE(myColumn, 'N', ''))
FROM ...
Number of times a particular character appears in a string
There's no direct function for this, but you can do it with a replace:
declare @myvar varchar(20)
set @myvar = 'Hello World'
select len(@myvar) - len(replace(@myvar,'o',''))
Basically this tells you how many chars were removed, and therefore how many instances of it there were.
Extra:
The above can be extended to count the occurences of a multi-char string by dividing by the length of the string being searched for. For example:
declare @myvar varchar(max), @tocount varchar(20)
set @myvar = 'Hello World, Hello World'
set @tocount = 'lo'
select (len(@myvar) - len(replace(@myvar,@tocount,''))) / LEN(@tocount)
How do you count the number of occurrences of a certain substring in a SQL varchar?
The first way that comes to mind is to do it indirectly by replacing the comma with an empty string and comparing the lengths
Declare @string varchar(1000)
Set @string = 'a,b,c,d'
select len(@string) - len(replace(@string, ',', ''))
Count the number of occurrences of a string in a VARCHAR field?
This should do the trick:
SELECT
title,
description,
ROUND (
(
LENGTH(description)
- LENGTH( REPLACE ( description, "value", "") )
) / LENGTH("value")
) AS count
FROM <table>
Count occurrences of character in a string and Group By with SQL
Try this, even I still don't know what you exactly want to do till now, but try it.
SELECT
book,
chapter,
group_concat(text) as text,
ROUND (
(
LENGTH(group_concat(text))
- LENGTH( REPLACE ( group_concat(text), "hello", "") )
) / LENGTH("hello")
) AS `count`
FROM my_table
GROUP BY chapter, book
How to count occurrences of a column value efficiently in SQL?
This should work:
SELECT age, count(age)
FROM Students
GROUP by age
If you need the id as well you could include the above as a sub query like so:
SELECT S.id, S.age, C.cnt
FROM Students S
INNER JOIN (SELECT age, count(age) as cnt
FROM Students
GROUP BY age) C ON S.age = C.age
Related Topics
Is SQL or Even Tsql Turing Complete
Calculate Working Hours Between 2 Dates in Postgresql
How to Create a Foreign Key in SQL Server
Custom Date/Time Formatting in SQL Server
Postgres Column "X" Does Not Exist
Maintaining Order in MySQL "In" Query
MySQL Equivalent of Decode Function in Oracle
SQL Selecting Rows by Most Recent Date with Two Unique Columns
How to Check If a String Is a Uniqueidentifier
What Can Cause an Oracle Rowid to Change
What's the Difference Between Rank() and Dense_Rank() Functions in Oracle
Find Overlapping Date Ranges in Postgresql
How to Create Table Using Select Query in SQL Server
How to Design a Database for User Defined Fields
How to Pass Parameters to Query in SQL (Excel)
How to Delete from Multiple Tables in the Same SQL Statement