mysql - 在 MYSQL 中的两个或多个临时表的表末尾显示总和/总计

标签 mysql sql union rollup

我得到了两个临时表,如下所示:

Tmp1:

 groups______active_members
   a              2
   b              3
   c              7

Tmp2:

 groups_______participants
   a              1
   b              2
   c              4

我用看起来像这样的代码加入了他们:

SELECT
  tmp1.group AS groups,
  tmp1.active AS active_members,
  tmp2.participiants 
    FROM(
      (SELECT  name AS 'group',
       COUNT(`id`) AS 'active'
       FROM table1
      ) tmp1
      INNER JOIN
      (SELECT  name AS 'group',
       COUNT(`id`) AS 'participiants'   
       FROM table2
      ) tmp2 
ON tmp1.group=tmp2.group)   

得到的结果是这样的:

 groups___active_members___participants
   a             2             1
   b             3             2
   c             7             4

我现在想要这样的结果:

 groups___active_members___participants
   a             2             1
   b             3             2
   c             7             4
 Total          12             7

请帮忙!!我也尝试过使用 UNION 和 WITH ROLLUP,但作为新手,我变得一无所知。非常感谢任何帮助。

最佳答案

SQL

SELECT tbl1.groups, tbl1.active_members, tbl2.participants
FROM tbl1
LEFT JOIN tbl2 ON tbl1.groups = tbl2.groups
UNION ALL
SELECT "Total", SUM(active_members), SUM(participants) 
FROM (SELECT tbl1.groups, tbl1.active_members, tbl2.participants
      FROM tbl1
      LEFT JOIN tbl2 ON tbl1.groups = tbl2.groups) AS tmptbl;

舍玛:

CREATE TABLE IF NOT EXISTS `tbl1` (
`id` int(11) NOT NULL,
  `groups` char(11) NOT NULL,
  `active_members` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `tbl2` (
`id` int(11) NOT NULL,
  `groups` char(11) NOT NULL,
  `participants` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

结果

enter image description here

关于mysql - 在 MYSQL 中的两个或多个临时表的表末尾显示总和/总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33627201/

相关文章:

php - 如何防止 PHP 中的 SQL 注入(inject)?

php - 如何在另一个更新查询中更新新表?

SQL 服务器 : delete where string value contains another value

MySQL 使用 order 排序而不使用 unio

sql-server - TSQL 方法选择不在基表中的行作为 UNION 的替代方法?

mySQL 如何逆透视动态列

php - 在MySQL多重插入中将数组值连接到字符串中

c# - 在 C# 中使用 Entity Framework、Mysql 和 LINQ to SQL 提交和回滚事务

php - 如何从MySQL记录中获取图像文件名?

sql - 如何在 SQL 查询中使用 LIKE 转义