Yii2 - 获取列的总和 [英] Yii2 - getting sum of a column
问题描述
我在指南中找到了这个,但不知道如何实现相同的
I found this in the guide, but have no idea how to implement the same
yii\db\Query::count();
返回 COUNT 查询的结果.其他类似的方法包括sum($q)
、average($q)
、max($q)
、min($q)
,其中支持所谓的聚合数据查询.$q
参数是必须的对于这些方法,可以是列名或表达式.
yii\db\Query::count();
returns the result of a COUNT query. Other
similar methods include sum($q)
, average($q)
, max($q)
, min($q)
, which
support the so-called aggregational data query. $q
parameter is mandatory
for these methods and can be either the column name or expression.
例如,我有一个带有列的表名billing":
Say for example I have a table name 'billing' with columns:
name amount
charge1 110.00
charge2 510.00
Total - 620.00
我如何使用
yii\db\Query::sum('amount');
我也试过了
$command = Yii::$app->db->createCommand("SELECT sum(amount) FROM billing");
yii\db\Query::sum($command);
但页面产生错误.
谢谢.
推荐答案
您尝试的第一部分代码似乎是在尝试使用查询生成器.在这种情况下,您必须创建一个查询实例,设置目标表,然后计算总和:
The first part of code you tried appears to be attempting to use Query Builder. In this case, you must create an instance of a query, set the target table, and then compute the sum:
通过查询生成器(http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html):
$query = (new \yii\db\Query())->from('billing');
$sum = $query->sum('amount');
echo $sum;
您尝试的第二部分代码似乎试图使用数据访问对象.在这种情况下,您可以编写原始 SQL 来查询数据库,但必须使用 queryOne()
、queryAll()
、queryColumn()
,或 queryScalar()
执行查询.queryScalar()
适用于这样的聚合查询.
The second part of code you tried appears to be attempting to use Data Access Objects. In this case, you can write raw SQL to query the database, but must use queryOne()
, queryAll()
, queryColumn()
, or queryScalar()
to execute the query. queryScalar()
is appropriate for an aggregate query such as this one.
通过数据访问对象(http://www.yiiframework.com/doc-2.0/guide-db-dao.html):
Via Data Access Objects (http://www.yiiframework.com/doc-2.0/guide-db-dao.html):
$command = Yii::$app->db->createCommand("SELECT sum(amount) FROM billing");
$sum = $command->queryScalar();
echo $sum;
这篇关于Yii2 - 获取列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!