繁体   English   中英

TSQL在字符串位置按位置计数“ 1”

[英]TSQL counting '1' in a string position, by positions

有这样的类别的字段:

如果将字符串设置为“ 1”,则该字符串中的每个位置代表“ 101011111000000101010011000101 ...”。 因此,“ 1”表示已设置,而“ 0”表示未设置。 我想计算具有最高“ 1”数量的类别,并按降序排列。

我当前的解决方案是这样的:

SELECT COUNT(SUBSTRING([Interests], 1, 1)) AS xcount, 1 AS ID
FROM [db1].[dbo].[Contacts]
WHERE SUBSTRING([Interests], 1, 1) = '1'
UNION
SELECT COUNT(SUBSTRING([Interests], 2, 1)) AS xcount, 2 AS ID
FROM [db1].[dbo].[Contacts]
WHERE SUBSTRING([Interests], 2, 1) = '1'
UNION
SELECT COUNT(SUBSTRING([Interests], 3, 1)) AS xcount, 3 AS ID
FROM [db1].[dbo].[Contacts]
WHERE SUBSTRING([Interests], 3, 1) = '1'
UNION
SELECT COUNT(SUBSTRING([Interests], 4, 1)) AS xcount, 4 AS ID
FROM [db1].[dbo].[Contacts]
WHERE SUBSTRING([Interests], 4, 1) = '1'
UNION
SELECT COUNT(SUBSTRING([Interests], 5, 1)) AS xcount, 5 AS ID
FROM [db1].[dbo].[Contacts]
WHERE SUBSTRING([Interests], 5, 1) = '1'
ORDER BY xcount DESC

有没有更好或更快速的方法来计算这些类别?

SELECT SUM(CASE WHEN SUBSTRING([Interests], _ID.ID, 1) = '1' THEN 1 ELSE 0 END) AS xcount, _ID.ID
FROM [db1].[dbo].[Contacts], (VALUES (1),(2),(3),(4),(5)) AS _ID(ID)
GROUP BY _ID.ID
ORDER BY xcount DESC

对于更多类别,只需增加_ID序列即可。

这将计算由0和1组成的字符串中的数字“ 1”

declare @s varchar(100) ='101011111000000101010011000101';
select cnt = len(@s) - len(replace(@s,'0',''))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM