我有一个包含10个字段的表,这些字段都可以在一个定义的集合中具有值。我只想从该表中选择10列重复相同值的次数不超过x次的记录。
示例:
id col1 col2 col3 col4 col5 col6 col7 col8 col9
--------------------------------------------------------
1 a b c d e f g h i
2 a a a b c d e f g
3 a a a a b c d e f
4 b c d e f g h i j
5 c c c c d c c f g
给定上面的示例表,我希望我的SELECT返回记录1、2和4。第3行和第5行都有四列或更多列具有相同的值。
到目前为止,我唯一的想法是连接所有10列,然后使用迭代的instr调用,但这将是非常静态的,并且对性能不友好。
感谢您的关注。
发布于 2015-09-18 00:21:59
您可以使用union all
将所有值放入一列,并对每个id
进行聚合。
select id from
(select id, col1 as col from tablename
union all
select id, col2 from tablename
union all
...
select id, col9 from tablename) t
group by id
having count(distinct col) > 7 --set this according to your need (10-x)
发布于 2015-09-18 01:50:55
在取消数据透视后,您可以使用两个级别的聚合来完成此操作:
select id
from (select id, col, count(*) as cnt
from ((select id, col1 as col from t) union all
(select id, col2 as col from t) union all
. . .
) t
group by id, col
) t
where cnt < 4
group by id;
在没有子查询的情况下,还有一种既麻烦又晦涩难懂的方法:
select t.*
from t
where length(replace(concat(col1, . . ., col9), col1, '') < 6 or
length(replace(concat(col1, . . ., col9), col2, '') < 6 or
. . .;
这会将列中的值连接在一起,然后删除每个值。仅当值为一个字符时,上述方法才有效。一个细微的变化适用于任何长度:
select t.*
from t
where replace(concat(concat_ws(',', col1, . . ., col9), ','),
concat(col1, ',')) not like '%,%,%,%,%,%,%' or
. . .
https://stackoverflow.com/questions/32641539
复制相似问题