我正在尝试比较两个 6 个数字的条目,每个数字可以是 0 或 1(即 100001 或 011101)。如果 6 个匹配中的 3 个匹配,我希望输出为 0.5。如果 6 个匹配中的 2 个匹配,我希望输出为 0.33 等。
请注意,位置很重要。仅当两个条目的第一个位置均为 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 中进行这种比较?提前致谢
最佳答案
看看这个例子。
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
它很粗糙,可能包含的内容超出了所需的内容,但显示了如何完成它。最好创建一个仅包含 1 到 1000 左右数字的 numbers
表,该表可以在需要数字序列的许多查询中重复使用。这样的表将取代(select .. union 在内连接中使用的虚拟表)
关于MySQL 字符串与百分比输出的比较(位置非常重要),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4856340/