mysql计数唯一的单元格组合,带有null

时间:2014-08-29 23:45:09

标签: php mysql sql

我试图使用PHP文件或SQL来通过一个大的data表来计算单元格组合的数量,并在新的data_sum表中计算它们。

我对PHP文件有一个想法:

$popdata = mysql_query("SELECT * FROM data");
    while($add = @mysql_fetch_array($popdata)){         
        $qitem1 = "SELECT * FROM data_sum WHERE item1='".$add['item1']."'";
        $ritem1 = mysql_query($qitem1);
        if(mysql_num_rows($ritem1) > 0){
            while($add2 = @mysql_fetch_array($ritem1)){
                $qitem2 = "SELECT * FROM data_sum WHERE item2='".$add['item2']."'";
                $ritem2 = mysql_query($qitem2);
                if (mysql_num_rows($ritem2) > 0){
                    $sql = "UPDATE Count=Count + 1 WHERE item1='".$add['item1']."' AND item2='".$add['item2']."'";
                    $update = mysql_query($sql);
                } else{
                    $sql = "INSERT INTO data_sum (item1, item2) VALUES('$item1', '$item2')";
                    $insert = mysql_query($sql);
            }
        } else{
            $sql = "INSERT INTO data_sum (item1, item2) VALUES('$item1', '$item2')";
            $insert = mysql_query($sql);
        }

如果我有桌子:

   `data`
item1  item2
  1           (this row counts to both the '1,2' duo as well as the '1,3')
  1     2
  1     3
  1     3
  2     3

我想把它压缩成类似的东西:

     `data_sum`
item1  item2  Count
  1      2      2
  1      3      3
  2      3      1

是的,我知道data中只有5行,计数总数为6.我希望其中没有任何内容的单元格计入每个可能的分支。有没有办法在SQL中使用COUNT或UNIQUE或DISTINCT执行此操作?谢谢!

1 个答案:

答案 0 :(得分:1)

, 通过分别对两个组进行计算,以下查询可以执行您想要的操作:

select base.item1, base.item2, base.cnt + coalesce(sum(extra.cnt), 0)
from (select item1, item2, count(*) as cnt
      from data
      where item1 is not null and item2 is not null
      group by item1, item2
     ) base join
     (select item1, item2, count(*) as cnt
      from data
      where item1 is null or item2 is null
      group by item1, item2
     ) extra
     on base.item1 = extra.item1 or
        base.item2 = extra.item2 or
        (extra.item1 is null and extra.item2 is null)
group by base.item1, base.item2, base.cnt;

Here是一个SQL小提琴。