我有一个包含常见组的行的表:
Id Name Group
1 ABC1 G1
2 ABC2 G1
3 ABC3 G1
4 AXX3 G2
在某些时候我知道我需要查询的组(例如 G1 )。然后,我需要在Name
过滤的行中查询Group
字段中最常见的字符。所以在这种情况下,我会得到ABC
。
这可以在一个查询中执行吗?我需要以最简单的方式做到这一点。
答案 0 :(得分:1)
你可以通过暴力来做到这一点:
select groupid,
(case when min(left(name, 10)) = max(left(name, 10)) then left(name, 10)
when min(left(name, 9)) = max(left(name, 9)) then left(name, 9)
when min(left(name, 8)) = max(left(name, 8)) then left(name, 8)
when min(left(name, 7)) = max(left(name, 7)) then left(name, 7)
when min(left(name, 6)) = max(left(name, 6)) then left(name, 6)
when min(left(name, 5)) = max(left(name, 5)) then left(name, 5)
when min(left(name, 4)) = max(left(name, 4)) then left(name, 4)
when min(left(name, 3)) = max(left(name, 3)) then left(name, 3)
when min(left(name, 2)) = max(left(name, 2)) then left(name, 2)
when min(left(name, 1)) = max(left(name, 1)) then left(name, 1)
end) as CommonPrefix
from t
group by groupid;
如果你不喜欢打字,你也可以这样做:
select groupid,
max(case when min(left(name, n.n)) = max(left(name, n.n)) then left(name, n.n) end)
from t cross join
(select 1 as n union all selet 2 union all select 3 . . .
) n
group by groupid;
(或使用where
子句获取一个组的信息。)对于此示例,只需将整数添加到n
子查询中,直到您要测试的长度。
答案 1 :(得分:0)
抱歉脏整数生成器:
select TT.g, max( MA ) from
(select t.g, max( left(t.Name,N.n ) ) MA, min( left(t.Name,N.n) ) MI
from t cross join
(select 0 as n union all select 1 union all select 3 union all
select 4 union all select 5 union all select 6 union all
select 6 union all select 7 union all select 8 union all select 9) N
group by t.g, N.n
) TT
where TT.MA = TT.MI
group by TT.g
结果:
+------+-----------+
| g | max( MA ) |
+------+-----------+
| G1 | ABC |
| G2 | AXX3 |
+------+-----------+
答案 2 :(得分:-1)
您可以通过计算所有内容来找到最大子字符串:
select k.common, k.setSize, k.number from
(select left(name, z.n) common, count(*) setSize, z.n number
from t
join (select 0 as n union all select 1 union all select 3 ...) as z
group by left(name, z.n)) k
order by k.setSize desc, k.number desc
将返回前x个字符中具有相同公共字符的条目数。第一行将为您提供最高子组后面的条目总数。