如何计算某个字符出现在 SQL 列中的次数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1144172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 02:52:13  来源:igfitidea点击:

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

sqltsqlchar

提问by RSolberg

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...

对于 SQL 数据库中的用户日志记录表,我跟踪报告请求中的一些参数。该报告允许将多个 ID 传递给它,我将所有这些 ID 存储在数据库列的单个列中。如果这是一组规范化的数据,肯定会有一个额外的表设置,但这是继承的......

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.

我现在被要求快速计算一个报告运行时传递给它的 ID 超过 2 个的次数。我可以轻松获得请求超过 1 个报告的记录数,因为它们都包含一个逗号。

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?

接下来我需要做的是计算逗号在列中出现的次数。你如何在 SQL 中做到这一点?

--count the number of times more than 1 report was requested in the record
select 
    count(*) as cnt
from
    [table]
where
    RequestedReportParams Like '%,%'

回答by AdaTheDev

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)

这只是将列的长度与逗号进行比较,将值的长度与逗号进行比较,以得出差异(即逗号的数量)

回答by mherren

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