MySQL-列中的所有值子集

时间:2014-12-01 11:53:42

标签: mysql stored-procedures

我有一个名为causality的表,它有两个数据类型(varchar,varchar)列(eventA,eventB),如下所述

  ----------------------------------------------
   eventA                |  eventB     
  ------------------------------------------------
  Wait - User            |  Resolved
  Wait                   |  Resolved
  Closed                 |  In Progress
  Wait - Vendor          |  Resolved
  Wait - Customer        |  Resolved
  Wait - Implementation  |  Assigned
  Wait - Implementation  |  Resolved
  Closed                 |  Awaiting Assignment
  Wait                   |  Assigned
  Wait - Customer        |  Awaiting Assignment
  Resolved               |  Unmatched
  Unmatched              |  In Progress
  Wait - Vendor          |  Assigned
  Wait - Customer        |  Assigned
  Wait - Implementation  |  Wait - Customer
  In Progress            |  Cancelled

  -----------------------------------------------

现在我想要eventB的所有子集,特别是eventA,就像Wait一样 - eventA列的实现有3个唯一值,因此将生成8个子集{{Assigned},{Resolved},{Wait - Customer},{Assigned ,已解决},{已分配,等待 - 客户},{已解决,等待 - 客户},{已分配,已解决,等待 - 客户},{}}

现在类似于eventA中的所有值,例如在eventA列中的Closed将有4个子集,Wait in eventA列将有4个子集,WaitA中的WaitA供应商将有4个子集,eventA列中的Wait -Customer将有8个子集,事件进展中eventA列将有2个子集,已解决的eventA列将有2个子集,eventA列中的Unmatched将有2个子集

因此输出表将有2列与因果关系表相似eventA将包含所有单值,eventB将包含evnetA中的值子集。

1 个答案:

答案 0 :(得分:1)

让我假设您有一个数字表,存储从0到足够大的数字的整数。然后,你可以用" bit-fiddling":

来做到这一点
select idc.id, n.n, group_concat(nc.team)
from numbers n cross join
     (select id, count(*) as cnt
      from not_connected
      group by id
     ) idc
     on n.n < idc.cnt left join
     (select id, team,
             (@rn := if(@id = id, @rn + 1,
                        if(@id := id, 1, 1)
                       )
             ) as rn
      from not_connected cross join
           (select @id := 0, @rn := 0) vars
      order by id, team
     ) nc
     on (n & (1 << nc.rn)) > 0
group by idc.id, n.n;

这首先为所有输出生成一行,给定id具有2 ^ n行,其中&#34; n&#34;是团队的数量。然后,每个位都映射到原始表中的团队名称。最后,group by汇总了给定数字和ID的值。

您需要一个数字表才能完成这项工作。只需为最大数量的团队生成足够大的一个。这是一种方法:

create table numbers as
    select (@rn := @rn + 1) as n
    from not_connected cross join
         (select @rn := 0);