【问题标题】:Find difference between two characters in SQL在 SQL 中查找两个字符之间的差异
【发布时间】:2021-01-02 06:47:19
【问题描述】:

我有一个有 2 列的表格

column1   column2
abcd      abdc
abcr      dfgh
cvge      cbge

我想知道 sql 查询以获得第三列,结果以这种方式显示 2 个字段之间的差异

column1   column2    calculated field
abcd      abdc       2
abcr      dfgh       0
cvge      cbge       3

【问题讨论】:

  • SQL 不是此类查询的合适工具,尽管它是可能的。您需要指出您正在使用的数据库。

标签: sql string difference word letter


【解决方案1】:

如果字段总是四个字符,您可以使用case 表达式。是这样的:

select ( (case when substr(field1, 1, 1) = substr(field2, 1, 1) then 1 else 0 end) +
         (case when substr(field1, 2, 1) = substr(field2, 2, 1) then 1 else 0 end) +
         (case when substr(field1, 3, 1) = substr(field2, 3, 1) then 1 else 0 end) +
         (case when substr(field1, 4, 1) = substr(field2, 4, 1) then 1 else 0 end)
       ) as calculated

请注意,所有数据库都支持substr() 的功能,但在某些数据库中,该功能可能有不同的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2012-02-09
    相关资源
    最近更新 更多