简体   繁体   English

如何用MySQL和PHP总结相同的值?

[英]How to sum same values with MySQL and PHP?

How can I sum the same values with MySQL? 如何用MySQL加总相同的值? This is my table for example: 这是我的表格例如:

--Id---------Name--
--1 ---------Value1
--2 ---------Value3
--3 ---------Value2
--4 ---------Value2
--5 ---------Value3
--6 ---------Value2

Now I should make a SQL query that sums the amount of same values, like: 现在我应该创建一个SQL查询,它总结相同值的数量,如:

SELECT SUM(IF(Name = 'Value1', SUM, 0)) AS Value1_total
   , SUM(IF(Name = 'Value2', SUM, 0)) AS Value2_total
   , SUM(IF(Name = 'Value3', SUM, 0)) AS Value3_total

Try: 尝试:

SELECT name, COUNT(name) amount FROM table 
GROUP BY name;

This will give you the actual value of the name field and the number of times its encountered. 这将为您提供名称字段的实际值及其遇到的次数。

$query = "SELECT name, COUNT(name) amount FROM table 
          GROUP BY name";
if (($result = mysqli_query($query))) {
  $data = array();
  while (($row = mysql_fetch_array($result,MYSQL_ASSOC))) {
    $data[$row['name']] = $row['amount'];
  }
  // then you can
  if (isset($data['Value1'])) {
    echo $data['Value1'];
  }
}

You may also try the following: 您也可以尝试以下方法:

SELECT a.s Value1_Total, b.s Value2_Total, c.s Value3_Total FROM t2,
(SELECT COUNT(name) s FROM t2 WHERE name = 'AAA') a,
(SELECT COUNT(name) s FROM t2 WHERE name = 'BBB') b,
(SELECT COUNT(name) s FROM t2 WHERE name = 'CCC') c;

Since you want the 3 sums returned in a single query, you're on the right track, query-wise, but it needs to be: 由于您希望在单个查询中返回3个总和,因此您在查询方面处于正确的轨道,但它必须是:

SELECT SUM(IF(Name = 'Value1',1,0)) AS Value1_total
                              ^--- change 'SUM' to 1

but the great issuer is that this is not very extensible. 但伟大的发行人是这不是非常可扩展的。 You need to have this SUM() construct for every field you want summed in this way. 您需要为每个要以这种方式求和的字段使用此SUM()构造。 It'd be more efficient to use a standard grouping query and then build this "horizontal" structure in your client-side code: 使用标准分组查询然后在客户端代码中构建这个“水平”结构会更有效:

SELECT Name, COUNT(id)
FROM yourtable
WHERE (Name IN ('Value1', 'Value2', 'Value3', ...))
GROUP BY Name

Edit: This should work, however it is very inefficient. 编辑:这应该工作,但效率很低。 You could probably use PIVOT if you want to make it more efficient. 如果你想提高它的效率,你可以使用PIVOT。

select 
   (select count(1) from table where name='Value1') as Value1_total
   (select count(1) from table where name='Value2') as Value2_total
   (select count(1) from table where name='Value3') as Value3_total
from 
  dual;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM