繁体   English   中英

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

[英]Show sum/total at the end of the table from two or more temporary tables in MYSQL

我已经获得了两个临时表,如下所示:

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;

结果

在此处输入图片说明

SELECT groups,active_members,participiants FROM (
SELECT 0 AS ord, 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)
UNION ALL
SELECT 1 AS ord, 'TOTAL',
  SUM(tmp1.active) AS active_members,
  SUM(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)
) AS tmp ORDER BY ord

暂无
暂无

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

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