mysql - 如何对 GROUP By 的结果求和

标签 mysql

我正在尝试添加 MySQL GROUP BY 的结果,但我无法做到这一点,这是我的代码:

SELECT country,SUM(visits) AS visits,SUM(visits-1) AS repetidos, COUNT(1) AS total FROM stats GROUP BY country HAVING COUNT(1) > 1

附上我的代码结果的图片以及我希望通过以下方式实现的目标:

enter image description here

我还会捕获我的表格:

enter image description here

最佳答案

也许您需要添加汇总

drop table if exists t;
create table t
(country varchar(2),visits int);
insert into t values
('co',12),('co',20),
('us',15),('us',1),('us',1);

SELECT country,SUM(visits) AS visits,
            SUM(visits-1) AS repetidos, 
            COUNT(1) AS total 
FROM  t 
GROUP BY country with rollup 
HAVING COUNT(1) > 1;

+---------+--------+-----------+-------+
| country | visits | repetidos | total |
+---------+--------+-----------+-------+
| co      |     32 |        30 |     2 |
| us      |     17 |        14 |     3 |
| NULL    |     49 |        44 |     5 |
+---------+--------+-----------+-------+
3 rows in set (0.00 sec)

关于mysql - 如何对 GROUP By 的结果求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58577642/

相关文章:

mysql - 无法使连接正常工作

mysql - Magento 2.1.7订单保存错误: SQLSTATE[42S02]:

mysql - Hierarchical Query 将中级类别归为顶级

mysql - Sql 查询 对于我的案例

mysql - 使用其他列中的值更新列

java - 构建一个监听数据库变化并调用其他方法的软件。我正在做正确的建筑吗?

mysql - sql没有正常执行

mysql - 通过联合选择获取多个字段?

mysql - 从 mysql 表中选择每隔一行作为男性/女性

MySQL在某些日期之间找到重复的行