2014-01-29 39 views
0

如何找到一定數量的index給定值如何一定數量的在SQL Server索引

例如,如果我的號碼是1001

我既需要一個目前的指數在1001 即, 14

我使用charindex但隨着這個我就能得到的只有charindex的第一1

+0

爲什麼不以關係格式存儲字符...... DigitId,Digit,Index'那麼你可以說'SELECT Index FROM Digits WHERE DigitId = 1001 AND Digit = 1'。這將比'SELECT Index FROM dbo.udfCrackDigitIndices(1001)'更好地表現明智。祝你好運索引表值UDF。 –

+0

@Santosh。 。 。你能解釋你想解決什麼問題嗎?可能有更好的解決方案。另外,數字總是四位數? –

+0

@GordonLinoff是的,它將總是4位數。它是一個數字的二進制轉換(最大15)。我正在嘗試一個解決方案,在這裏[http://stackoverflow.com/questions/21428317/an-sql-函數爲基數轉換-算法FFT/21431159#21431159] – Santosh

回答

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 ║ 
╚══════╩═══════╝ 
0

如果人數只有4位數,那麼我建議一個明確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