SQLite SUM()函数

SQLite SUM()函数用于返回表达式或给定数字列的总和。

语法

SELECT SUM(aggregate_expression)  
FROM tables  
[WHERE conditions];

SUM()函数中使用GROUP BY子句时的语法:

SELECT expression1, expression2, ... expression_n  
SUM(aggregate_expression)  
FROM tables  
[WHERE conditions]  
GROUP BY expression1, expression2, ... expression_n;

示例1:

假设有一个名为student的表,具有以下数据:

《SQLite SUM()函数》

student表中检索AGE小于24的学生总费用:

SELECT SUM(FEES) AS "Total Fees"  
FROM STUDENT  
WHERE AGE < 24;

执行上面查询代码,得到以下结果 –

sqlite> SELECT SUM(FEES) AS "Total Fees"
   ...> FROM STUDENT
   ...> WHERE AGE < 24;
34000.0
sqlite>

示例2:

使用具有数学公式的SUM()函数,求每个月的学生总费用 –

SELECT SUM(FEES / 12) AS "Total Monthly Fees"  
FROM STUDENT;

执行上面代码,得到以下结果 –

sqlite> SELECT SUM(FEES / 12) AS "Total Monthly Fees"
   ...> FROM STUDENT;
14083.3333333333
sqlite>

示例3:

计算每个地址的学生总人数,按学生地址(Address)分组。

student表中检索地址,并按地址分组并查找相应费用的总和。

SELECT ADDRESS, SUM(FEES) AS "Total Salary"  
FROM STUDENT  
WHERE ID > 0
GROUP BY ADDRESS;

执行上面代码,得到以下结果 –

sqlite> SELECT ADDRESS, SUM(FEES) AS "Total Salary"
   ...> FROM STUDENT
   ...> WHERE ID > 0
   ...> GROUP BY ADDRESS;
Beijing|15000.0
Guangzhou|70000.0
Haikou|35000.0
Shanghai|2000.0
Shengzhen|38000.0
Shenzhen|9000.0
sqlite>

        原文作者:SQLite教程
        原文地址: https://www.yiibai.com/sqlite/sum.html
        本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
    点赞

    发表评论

    电子邮件地址不会被公开。 必填项已用*标注