mysql - SQL - 行中不同数量的元素
问题描述
假设我有三列:dim1、dim2、dim3 - 所有的 int 类型值。
我想计算行中不同值的数量- 因此对于 ID #13 dim1=20、dim2=30 和 dim3=20 的行,存储在新创建的列中的值将等于 2。
这有可能吗?我在多列上尝试了 COUNT DISTINCT 的各种组合,到目前为止还没有奏效。
解决方案
聚合函数,例如跨行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
推荐阅读
- php - cakephp登录或条件
- php - 如何更改html锚标记查询字符串
- django - tornado deploy django 和日志重复输出
- salesforce - 为什么无法在salesforce的公共站点中显示某些列?
- tcp - 使用 tcpserversink 将 gstreamer 流式传输到 vlc
- javascript - 名称属性选择器不起作用
- vba - 循环遍历具有多个 for 循环的工作表,并且内部的 If 函数不起作用
- r - 外部函数调用中的参数过多
- vue.js - 在组件中的事件上将类应用于 VueJs 中的 index.html
- google-apps-script - 通过录制的 Google Script 未出现在宏菜单中