Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of times a character appears in a SQL column?

Tags:

sql

tsql

char

For a user logging table I have in a SQL database, I track the some of the parameters off of a report request. The report allows multiple ID's to be passed to it and I store all of those in a single column in the database column. If this were to be a normalized set of data, there would definitely be an additional table setup for this, but this is what was inherited...

I've now been asked to give a quick count of the number of times a report was run with more than 2 ID's passed to it. I can easily get the number of records that have more than 1 report requested because they all include a comma.

What I need to do next is count the number of times a comma appears in a column. How do you do this in SQL?

--count the number of times more than 1 report was requested in the record select      count(*) as cnt from     [table] where     RequestedReportParams Like '%,%' 
like image 796
RSolberg Avatar asked Jul 17 '09 15:07

RSolberg


People also ask

How do you count the number of times a value appears in a column SQL?

The MySQL COUNT() function allows you to count how many times a certain value appears in your MySQL database. The function can also help you to count how many rows you have in your MySQL table. The function has one expression parameter where you can specify the condition of the query.


2 Answers

SELECT LEN(RequestedReportParams) - LEN(REPLACE(RequestedReportParams, ',', '')) FROM YourTable WHERE ..... 

This is simply comparing the length of the column with the commas, with the length of the value with the commas removed, to give you the difference (i.e. the number of commas)

like image 144
AdaTheDev Avatar answered Sep 19 '22 19:09

AdaTheDev


It seems the quick and dirty way to answer the question you've been asked would be to do this:

select      count(*) as cnt FROM      [table] WHERE      RequestedReportParams Like '%,%,%' 
like image 32
Billy Herren Avatar answered Sep 17 '22 19:09

Billy Herren