MySQL 字符串与百分比输出的比较
我试图比较两个 6 个数字的条目,每个数字可以是 0 或 1(即 100001 或 011101)。如果 6 个匹配中的 3 个匹配,我希望输出为 0.5。如果 6 个匹配中的 2 个匹配,我希望输出为 0.33 等。
以下是创建表的 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, 111111);
,我希望输出比较两个字符串,这两个字符串共享 50% 的字符,并输出 50%。
SQL 中可以进行这种比较吗?提前致谢
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.
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, 111111);
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将返回两个字符串中相等 1 位的百分比:
当您将位字段存储为转换为数字的基数 2 表示形式时,我们首先需要进行转换:
conv(a.string, 2, 10)
,conv(b.string, 2, 10)
。然后我们只保留每个字段中为 1 的位: conv(a.string, 2, 10) & conv(b.string, 2, 10)
我们对它们进行计数:
bit_count(conv(a.string, 2, 10) & conv(b.string, 2, 10))
最后我们只计算百分比:
bit_count(conv(a.string, 2, 10) & conv(b.string, 2, 10)) / 6 * 100
。对于
111000
和111111
,查询返回50
。这是另一个版本,也计算匹配的零:
请注意,虽然此解决方案有效,但您实际上应该像这样存储此字段:
或者更新现有数据:
然后此查询给出相同的结果(如果您按照描述更新了数据)上面):
也计算零:(
用位域的大小替换 6)
This returns the percentage of equal 1 bits in both strings:
As you store your bitfields as base 2 representation converted to numbers, we first need to do conversions:
conv(a.string, 2, 10)
,conv(b.string, 2, 10)
.Then we keep only bits that are 1 in each field:
conv(a.string, 2, 10) & conv(b.string, 2, 10)
And we count them:
bit_count(conv(a.string, 2, 10) & conv(b.string, 2, 10))
And finally we just compute the percentage:
bit_count(conv(a.string, 2, 10) & conv(b.string, 2, 10)) / 6 * 100
.The query returns
50
for111000
and111111
.Here is an other version that also counts matching zeros:
Note that, while this solution works, you should really store this field like this instead:
Or to update existing data:
Then this query gives the same results (if you updated your data as described above):
And to count zeros too:
(replace
6
s by the size of your bitfields)由于您将它们存储为数字,因此您可以这样做
Since you are storing them as numbers, you can do this