5

我有一个表,其中一些行具有公共组:

Id    Name    Group
1     ABC1    G1
2     ABC2    G1
3     ABC3    G1
4     AXX3    G2

在某些时候,我知道我需要查询的组(例如G1 )。Name然后我需要在由它们过滤的行中查询字段中最常见的字符Group。所以在这种情况下,我会得到ABC.

这可以在一个查询中执行吗?我需要以最简单的方式做到这一点。

4

3 回答 3

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子查询添加整数,直到您想要测试的长度。

于 2013-08-10T16:40:05.483 回答
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      |
+------+-----------+
于 2013-08-10T16:53:03.853 回答
-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 个字符中具有相同公共字符的条目数。第一行将为您提供条目总数,然后是顶部子组。

于 2013-08-10T16:46:47.213 回答