How to count the number of times a character appea

2020-02-08 07:20发布

问题:

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 '%,%'

回答1:

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)



回答2:

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 '%,%,%'


标签: sql tsql char