mysql对比时间段百分比,MySQL字符串比较与百分比输出(位置非常重要

该博客讨论如何在SQL中进行两个包含六个二进制位的字符串比较,以确定它们的匹配程度。通过创建一个示例,展示了如何使用子字符串函数和条件语句计算匹配的位数,并将结果转换为百分比形式。这种方法适用于需要在数据库查询中计算字符串相似度的情况。
摘要由CSDN通过智能技术生成

I am trying to compare two entries of 6 numbers, each number which can either can be zero or 1 (i.e 100001 or 011101). If 3 out of 6 match, I want the output to be .5. If 2 out of 6 match, i want the output to be .33 etc.

Note that position matters. A match only occurs when both entries have a 1 in the first position, both have a 0 in the second position etc.

Here are the SQL commands to create the table

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);

My desired output to compare the two strings, which share 50% of the characters, and output 50%.

Is it possible to do this sort of comparison in SQL? Thanks in advance

解决方案

Have a look at this example.

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

It is crude and probably included more than required but shows how it can be done. It is better to create a numbers table with just numbers from 1 to 1000 or so, that can be used repeatedly in many queries where a number sequence is required. Such a table will replace the (select .. union virtual table used in the inner join)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值