0

How to find an index of a certain number for a given value

For example, if my number is 1001

I need index of both the one's present in 1001 Ie. 1 and 4

I am using charindex.But with this I am able to get only charindex of first 1.

4

2 回答 2

0
Declare @String VARCHAR(10) = '1001'

SELECT CHARINDEX('1', @String)  AS FirstOne
      ,CHARINDEX('1', @String, CHARINDEX('1', @String)+1) NextOne

结果

FirstOne  NextOne
   1         4

CHARINDEX 有一个可选的第三个参数 [起始索引]

CHARINDEX ( expressionToFind ,expressionToSearch [ , start_location ] )

或者你可以做这样的事情......

Declare @String VARCHAR(10) = '110101'


DECLARE @Table TABLE ([Char] CHAR(1), [INDEX] INT)      
DECLARE @ChartoSearch CHAR(1) = '1'      
DECLARE @i INT = 0      

WHILE (LEN(@String) >= @i)
BEGIN
     INSERT INTO @Table ([Char], [INDEX])
     SELECT @ChartoSearch,CHARINDEX(@ChartoSearch, @String, @i)
     SET @i = @i + 1;
END

SELECT DISTINCT * FROM @Table

结果集

╔══════╦═══════╗
║ Char ║ INDEX ║
╠══════╬═══════╣
║    1 ║     1 ║
║    1 ║     2 ║
║    1 ║     4 ║
║    1 ║     6 ║
╚══════╩═══════╝
于 2014-01-29T12:17:13.813 回答
0

如果数字只有四位数,那么我建议明确case声明:

select (case when number = '0000' then 0
             when number = '0001' then 1
             when number = '0010' then 1
             when number = '0011' then 2
             when number = '0100' then 1
             when number = '0101' then 2
             when number = '0110' then 2
             when number = '0111' then 3
             when number = '1000' then 1
             when number = '1001' then 2
             when number = '1010' then 2
             when number = '1011' then 3
             when number = '1100' then 2
             when number = '1101' then 3
             when number = '1110' then 3
             when number = '1111' then 4
      end) as NumOnes

或者,像这样进行计算:

select ((case when number like '1%' then 1 else 0 end) +
        (case when number like '_1%' then 1 else 0 end) +
        (case when number like '__1%' then 1 else 0 end) +
        (case when number like '___1%' then 1 else 0 end)
       ) as NumOnes

您还可以将数字作为数字执行以下操作:

select ((case when number & 1 > 0 then 1 else 0 end) +
        (case when number & 2 > 0 then 1 else 0 end) +
        (case when number & 4 > 0 then 1 else 0 end) +
        (case when number & 8 > 0 then 1 else 0 end)
       ) as NumOnes
于 2014-01-29T14:46:24.140 回答