2011-01-31 74 views
0

我試圖比較6個數字的兩個條目,每個數字可以是0或1(即100001或011101)。如果6個匹配中的3個匹配,我想輸出爲.5。如果6個匹配中的2個,我希望輸出爲.33等。MySQL字符串與百分比輸出的比較(位置非常重要

注意位置很重要只有當兩個條目在第一個位置都有1時,在第二位置具有0等

下面是SQL命令以創建表

CREATE TABLE sim 
(sim_key int, 
string int); 

INSERT INTO sim (sim_key, string) 
VALUES (1, 111000); 

INSERT INTO sim (sim_key, string) 
VALUES (2, 101101); 

我想要的輸出用於比較兩個字符串,它們共享50%的字符,並輸出50%。

是否有可能在SQL中進行這種比較?在此先感謝

+0

http://dev.mysql.com/doc/refman/5.5/en/bit-functions.html位與

...聽起來像是一個功能的工作。 – 2011-01-31 21:35:56

+0

我是SQL新手,你在說什麼類型的函數? – Spencer 2011-01-31 21:37:22

回答

2

看看這個例子。

CREATE TABLE sim  (sim_key int,  string int); 
INSERT INTO sim (sim_key, string)  VALUES (1, 111000); 
INSERT INTO sim (sim_key, string)  VALUES (2, 101101); 

select a.string A, b.string B, 
    sum(case when Substring(A.string,Pos,1) = Substring(B.string,Pos,1) then 1 else 0 end) Matches, 
    count(*) as RowCount, 
    (sum(case when Substring(A.string,Pos,1) = Substring(B.string,Pos,1) then 1 else 0 end)/
    count(*) * 100.0) as PercentMatch 
from sim A 
cross join sim B 
inner join (
    select 1 Pos union all select 2 union all select 3 
    union all select 4 union all select 5 union all select 6) P 
     on P.Pos between 1 and length(A.string) 
where A.sim_key= 1 and B.sim_key = 2 
group by a.string, b.string 

這是粗糙的,可能包含超過要求但顯示如何完成。最好創建一個numbers表,其中只有1到1000左右的數字,可以在需要數字序列的許多查詢中反覆使用。這樣的表將取代(選擇..內聯合中使用的聯合虛擬表)