多列的Mysql组合

时间:2014-01-20 15:56:46

标签: mysql sql mysqli

我的表格格式为

item  A  B  C  D
i1    4  0  2  0
i2    0  2  1  0
i3    2  0  0  2
i4    3  0  1  1

而且,我正在寻找输出,其中两列是组合的,如果两个元素值都是> 0,则输出值取为1.总计数从所有记录计算

w1 w2   out
A  B    0
A  C    2
A  D    2
B  C    1
B  D    0
C  D    1

i,e,对于列(A,C)> 0,只有i1和i4满足。所以out = 2

到目前为止,我通过查询每个项目然后在php中总结值来解决这个问题。这完全可以通过sql查询吗?

1 个答案:

答案 0 :(得分:2)

您可以在SQL中执行此操作,但我认为您仍需要考虑所有不同的组合。以下是使用union all和条件聚合的一种方法:

select col1name, col2name,
       sum(col1 > 0 and col2 > 0)
from (select 'A' as col1name, 'B' as col2name, A as col1, B as col2
      from t
      union all
      select 'A', 'C', A, C
      from t
      union all
      select 'A', 'D', A, D
      from t
      union all
      select 'B', 'C', B, C
      from t
      union all
      select 'B', 'D', B, D
      from t
      union all
      select 'C', 'D', C, D
      from t
     ) t

编辑:

如果您取消数据,还有另一种方法。这从这个查询开始:

select item, n.colname,
       (case when n.colname = 'A' then A
             when n.colname = 'B' then B
             when n.colname = 'C' then C
             else D
        end) as colval
from t cross join
     (select ';A' as colname union all select 'B' union all select 'C' union all select 'D'
     );

我们现在可以对查询进行自联接以获取所有组合并聚合以获得结果:

select col1.colname, col2.colname,
       sum(col1.colval > 0 and col2.colval > 0)
from (select item, n.colname,
             (case when n.colname = 'A' then A
                   when n.colname = 'B' then B
                   when n.colname = 'C' then C
                   else D
              end) as colval
      from t cross join
           (select ';A' as colname union all select 'B' union all select 'C' union all select 'D'
           )
     ) col1 join
     (select item, n.colname,
             (case when n.colname = 'A' then A
                   when n.colname = 'B' then B
                   when n.colname = 'C' then C
                   else D
              end) as colval
      from t cross join
           (select ';A' as colname union all select 'B' union all select 'C' union all select 'D'
           )
     ) col2
     on col1.item = col2.item and
        col1.colname < col2.colname
group by col1.colname, col2.colname;

如果您有四列以上,则此版本更简单。第一种方法中的组合数量很快就会变得很麻烦。