如何计算一个字符在 SQL 列中出现的次数? [英] How to count the number of times a character appears in a SQL column?

查看:19
本文介绍了如何计算一个字符在 SQL 列中出现的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

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

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

推荐答案

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)

这篇关于如何计算一个字符在 SQL 列中出现的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆