我有一个表,它可能在两列(B列和/或C列)中的一列中包含搜索值。我想基于a列生成一个摘要,显示每个人所选搜索值(如x)在任一列中出现的次数。我想计算两列的总数。

+--------+------+----+
|  name  | B    | C  |
+--------+------+----+
| john   | x    | z  |
| john   | x    | x  |
| john   | y    | x  |
| peter  | x    | z  |
| peter  | x    | z  |
| amanda | x    | x  |
| amanda | x    | x  |
| amanda | x    | x  |
| amanda | x    | y  |
| amanda | x    | y  |
+--------+-----------+

在上面的例子中,假设我的搜索值是x,我想计算x在B列和/或C列中出现的次数。我还想产生总计,并产生这个输出:
Name   B  C

john   2  2
peter  2  0
amanda 5  3
total  9  5

我可以对每个列分别这样做:
     SELECT name, COUNT(*) as count FROM table
          WHERE A = 'x'
          GROUP BY name
          ORDER BY count DESC";

     SELECT name, COUNT(*) as count FROM table
          WHERE B = 'x'
          GROUP BY name
          ORDER BY count DESC";

然后,我可以循环对每个列的输出执行单独的抓取并将它们组合起来,但是我想知道是否有方法在一个mysql语句中对这两列进行检查和计数?

最佳答案

如果要分别计算每列的总和,可以使用以下(SQL Fiddle):

(
  SELECT MTA.Name, Sum(MTA.B = 'x') AS BSum, Sum(MTA.C = 'x') AS CSum
  FROM MyTable MTA
  GROUP BY MTA.Name
)
UNION
(
  SELECT 'Total' AS name, Sum(MTB.B = 'x') AS BSum, Sum(MTB.C = 'x') AS CSum
  FROM MyTable AS MTB
)

或者,如果希望两列的总和合并,则可以执行以下操作(SQL Fiddle):
(
  SELECT MTA.Name, Sum(MTA.B = 'x') + Sum(MTA.C = 'x') AS PersonTotal
  FROM MyTable MTA
  GROUP BY MTA.Name
)
UNION
(
  SELECT 'Total' AS name, Sum(MTB.B = 'x') + Sum(MTB.C = 'x') AS PersonTotal
  FROM MyTable AS MTB
)

关于php - MySQL汇总两行之一中包含值的所有行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19531677/

10-09 14:21