問題描述
如何計算給定字符串中重復 $ 字符的出現次數.
How do I count the number of occurrences of repeated $ character in the given strings.
例如:
- String = '$$$$ABC$$$DE$$$' -->答案是 4,3,3
- String = '###$$%%ANE$$$$$' -->答案是 2,5
我不知道怎么做所以沒有做任何嘗試.
I have no idea how to do it so did not do any attempts.
感謝您的幫助.
用于復制:
- DDL 和插入:
Create table xyz(text varchar(200));
Insert into xyz values('$$$$ABC$$$DE$$$');
Insert into xyz values('###$$%%ANE$$$$$');
我需要做的:計算'$'的重復次數
What I need to do: Count the repeated number of '$'
所需的輸出,基于上面 #1 中的示例數據.
Desired output, based on the sample data in #1 above.
text = '$$$$ABC$$$DE$$$' -->答案是 4,3,3
text = '###$$%%ANE$$$$$' -->答案是 2,5
text = '$$$$ABC$$$DE$$$' --> Answer is 4,3,3
text = '###$$%%ANE$$$$$' --> Answer is 2,5
SQL Server 版本:Microsoft SQL Server 2019 (RTM) - 15.0.2000.5
SQL Server version: Microsoft SQL Server 2019 (RTM) - 15.0.2000.5
推薦答案
請嘗試以下解決方案.它將從 SQL Server 2017 開始工作.
Please try the following solution. It will work starting from SQL Server 2017 onwards.
它基于 TRANSLATE()
函數以及 XML 和 XQuery 的使用.
It is based on use of the TRANSLATE()
function, and XML and XQuery.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, tokens VARCHAR(30));
INSERT INTO @tbl (tokens) VALUES
('$$$$ABC$$$DE$$$'), --> Answer is 4,3,3
('###$$%%ANE$$$$$'); --> Answer is 2,5
-- DDL and sample data population, end
DECLARE @separator CHAR(1) = SPACE(1);
;WITH cte AS
(
SELECT *
, REPLACE(TRANSLATE(tokens, '$', SPACE(1)),' ','') AS JunkCharacters
FROM @tbl
)
SELECT *
, REPLACE(TRY_CAST('<root><r><![CDATA[' +
REPLACE(TRANSLATE(tokens, TRIM(JunkCharacters), SPACE(LEN(TRIM(JunkCharacters)))), @separator, ']]></r><r><![CDATA[') +
']]></r></root>' AS XML)
.query('
for $x in /root/r[text()]
return data(string-length($x))
').value('.', 'VARCHAR(20)'), SPACE(1), ',') AS CleansedTokensCounter
FROM cte;
輸出
+----+-----------------+----------------+-----------------------+
| ID | tokens | JunkCharacters | CleansedTokensCounter |
+----+-----------------+----------------+-----------------------+
| 1 | $$$$ABC$$$DE$$$ | ABCDE | 4,3,3 |
| 2 | ###$$%%ANE$$$$$ | ###%%ANE | 2,5 |
+----+-----------------+----------------+-----------------------+
這篇關于計算給定字符串中重復字符的數量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!