首页 > 解决方案 > SQL - 行中不同数量的元素

问题描述

假设我有三列:dim1、dim2、dim3 - 所有的 int 类型值。

我想计算中不同值的数量- 因此对于 ID #13 dim1=20、dim2=30 和 dim3=20 的行,存储在新创建的列中的值将等于 2。

这有可能吗?我在多列上尝试了 COUNT DISTINCT 的各种组合,到目前为止还没有奏效。

标签: mysqlsql

解决方案


聚合函数,例如跨行count工作,而不是跨列工作。我看到两种方法可以解决这个问题:

1)您可以使用案例语句来解决这个问题(这个解决方案变得更加复杂,超过 3 个字段):

select dim1, dim2, dim3,
       case when dim1 <> dim2 then 1 else 0 end
       + case when dim1 <> dim3 then 1 else 0 end
       + case when dim2 <> dim3 then 1 else 0 end as cnt
from your_table

2)假设您在每一行都有某种 ID,您可以使用union将您的数据转换为更多的键/值集,这将允许您使用count

select dim1, dim2, dim3, cnt
from your_table
     join (select id, count(distinct dim) as cnt from
                  (select id, dim1 as dim from your_table
                   union all 
                   select id, dim2 from your_table
                   union all 
                   select id, dim3 from your_table)
           group by id) c
     on your_table.id = c.id

推荐阅读