SQL 如何使用sql查找字符串中特定字符的出现次数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/287373/
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
How can you find the number of occurrences of a particular character in a string using sql?
提问by Mladen Prajdic
How can you find the number of occurrences of a particular character in a string using sql?
如何使用sql查找字符串中特定字符的出现次数?
Example: I want to find the number of times the letter ‘d' appears in this string.
示例:我想查找字母 'd' 在此字符串中出现的次数。
declare @string varchar(100)
select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'
回答by Mladen Prajdic
Here you go:
干得好:
declare @string varchar(100)
select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'
SELECT LEN(@string) - LEN(REPLACE(@string, 'd', '')) AS D_Count
回答by Rob Farley
If you want to make it a little more general, you should divide by the length of the thing you're looking for. Like this:
如果你想让它更笼统一点,你应该除以你要找的东西的长度。像这样:
declare @searchstring varchar(10);
set @searchstring = 'Rob';
select original_string,
(len(orginal_string) - len(replace(original_string, @searchstring, ''))
/ len(@searchstring)
from someTable;
This is because each time you find 'Rob', you remove three characters. So when you remove six characters, you've found 'Rob' twice.
这是因为每次找到“Rob”时,都会删除三个字符。因此,当您删除六个字符时,您已经找到了两次“Rob”。
回答by Tiggyboo
For all you Sybase ASE 15 dinosaurs our there, you will need to replace '' with null, i.e.
对于我们那里的所有 Sybase ASE 15 恐龙,您需要将 '' 替换为 null,即
SELECT LEN(@string) - LEN(REPLACE(@string, 'd', null)) AS D_Count