在不可能引用数据的情况下,计算每列中的差异数



我需要计算一组已知数据之间差异的总和。php中的等效项是CCD_ 1。Mysql有可能做到这一点吗?我有一组数据要与表中的其他字段列进行比较。

我要比较的数据是columnA : 3, columnB : 6, columnC : 4

测试表是:

   ID       columnA     columnB    columnC
   1           2           6         1
   2           6           1         3
   3           3           6         4

预期结果:

 ID     numbersofdifferences
  3            0
  1            2
  2            3

感谢您的帮助,Jeisca

这不一定是最干净的,但您可以使用带有CASE表达式的聚合函数:

select id,
    sum(case when columna = 3 then 0 else 1 end) +
    sum(case when columnb = 6 then 0 else 1 end) +
    sum(case when columnc = 4 then 0 else 1 end) TotalDiff
from yourtable
group by id;

请参阅SQL Fiddle with Demo。

编辑,这也可以在没有聚合功能的情况下完成:

select id,
    (case when columna = 3 then 0 else 1 end) +
    (case when columnb = 6 then 0 else 1 end) +
    (case when columnc = 4 then 0 else 1 end) TotalDiff
from yourtable;

请参阅演示

没有内置函数来做这样的事情,但您可以手动完成。

select
    id,
    case columnA when $columnA then 1 else 0 end +
      case columnB when $columnB then 1 else 0 end +
      case columnC when $columnC then 1 else 0 end differences
  from
    myTable

但如果你想把它们按顺序排列,你会想要一个子选择

select * from 
  (
    select
        id,
        case columnA when $columnA then 1 else 0 end +
          case columnB when $columnB then 1 else 0 end +
          case columnC when $columnC then 1 else 0 end differences
      from
        myTable
  ) sqlRequiresNameHere
  order by differences

最新更新