Mysql根据相同的值计算多个列

时间:2014-08-14 15:21:43

标签: mysql sql

我有以下表格

    A               B
    Yes             OOS
    No              No
    OOS             Yes
    OOS             No
    Yes             No

我想做以下

Criteria        A               B
Yes             2               1
No              1               3
OOS             2               1

我可以使用像

这样的列来实现这一目标
Criteria        A 
Yes             2 
No              1 
OOS             2 

以下是我必须实现的目标:

SELECT A, count(A) FROM temp_db GROUP BY A;

3 个答案:

答案 0 :(得分:0)

您需要将值添加到单个列中,以便使用group by。这是一种方法:

select criteria, sum(A) as A, sum(B) as B
from ((select A as criteria, 1 as A, 0 as B
       from liketable
      ) union all
      (select B, 0, 1
       from liketable
      )
     ) t
group by criteria;

使用union all方法是MySQL中最安全的方法,如果并非所有criteria都在两列中。以下是一个轻微的调整,可能会在性能上更好一点:

select criteria, sum(A) as A, sum(B) as B
from ((select A as criteria, count(*) as A, 0 as B
       from liketable
       group by A
      ) union all
      (select B, 0, count(*)
       from liketable
       group by B
      )
     ) t
group by criteria;

通常对一半数据进行两次聚合比对所有数据进行更大的聚合更有效。

答案 1 :(得分:0)

select val, sum(cntA), sum(cntB)
from (SELECT A as val, count(A) as cntA,        0 as cntB FROM temp_db GROUP BY A;
      union all
      SELECT B as val,        0 as cntA, count(B) as cntB FROM temp_db GROUP BY B)
group by val;

答案 2 :(得分:0)

对于此示例数据,您可以使用派生表的连接来执行此操作:

SELECT qa.Criteria, qa.A, qb.B FROM
(SELECT A AS Criteria, count(A) AS A FROM temp_db GROUP BY A) qa
FULL OUTER JOIN 
(SELECT B AS Criteria, count(B) AS B FROM temp_db GROUP BY B) qb
  ON qa.Criteria=qb.Criteria

但是如果A列中缺少标准,它们将不会出现在此查询的结果中,您将需要其他人建议的UNION ALL方法。