在sql中将UNION的结果合并在一起

时间:2017-05-30 21:08:48

标签: mysql sql

我正在尝试结合来自

的联盟的结果
SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) as total 
FROM projects
WHERE terms >= '2017/01/01' AND Building_designer='SOMEPERSON'
GROUP BY MONTH(terms)
UNION
SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) as total 
FROM archive
WHERE terms >= '2017/01/01' AND Building_designer='SOMEPERSON'
GROUP BY MONTH(terms)

我得到以下结果:来自SQL语句的结果

RESULTS FROM THE SQL STATEMENT

我正在努力使其总数将是本月多个实例的组合。 sql表完全相同。

这就是我想要的样子:

enter image description here

4 个答案:

答案 0 :(得分:1)

FULL OUTER JOIN是理想的。但在你的情况下,让我们做两个级别的聚合:

SELECT month, MAX(total_projects) as total_projects, MAX(total_archive) as total_archive
FROM ((SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) as total_projects, 0 as total_archive
       FROM projects
       WHERE terms >= '2017/01/01' AND Building_designer = 'SOMEPERSON'
       GROUP BY MONTH(terms)
      ) UNION ALL
      (SELECT MONTHNAME(terms) AS month, 0, COUNT(DISTINCT project_num
       FROM archive
       WHERE terms >= '2017/01/01' AND Building_designer = 'SOMEPERSON'
       GROUP BY MONTH(terms)
      )
     ) pa
GROUP BY month
ORDER BY month;

编辑:

糟糕。您只需要一列。如果您想计算每月不同项目的数量,请执行union all,然后将结果合并到下一个更高级别:

SELECT month, COUNT(DISTINCT project_num) as total
FROM ((SELECT MONTHNAME(terms) AS month, project_num
       FROM projects
       WHERE terms >= '2017/01/01' AND Building_designer = 'SOMEPERSON'
      ) UNION ALL
      (SELECT MONTHNAME(terms) AS month, project_num
       FROM archive
       WHERE terms >= '2017/01/01' AND Building_designer = 'SOMEPERSON'
      )
     ) pa
GROUP BY month
ORDER BY month;

答案 1 :(得分:0)

快速思考就是做这样的事情。您基本上想要对每个表中的计数求和。

select month, sum(total) from 
(
SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) as total FROM projects WHERE terms >= '2017/01/01' AND Building_designer='SOMEPERSON' GROUP BY MONTH(terms)
UNION
SELECT MONTHNAME(terms) AS month, COUNT(DISTINCT project_num) as total FROM archive WHERE terms >= '2017/01/01' AND Building_designer='SOMEPERSON' GROUP BY MONTH(terms)
) group by month;

答案 2 :(得分:0)

转换为派生表,放置别名然后聚合

select 
x.month,
sum(x.total) [Total]
from (
SELECT
  MONTHNAME(terms) AS month,
  COUNT(DISTINCT project_num) AS total
FROM projects
WHERE terms >= '2017/01/01'
AND Building_designer = 'SOMEPERSON'
GROUP BY MONTH(terms)
UNION
SELECT
  MONTHNAME(terms) AS month,
  COUNT(DISTINCT project_num) AS total
FROM archive
WHERE terms >= '2017/01/01'
AND Building_designer = 'SOMEPERSON'
GROUP BY MONTH(terms)
) x

group by x.month

答案 3 :(得分:0)

您可以尝试在整个查询中创建求和表达式。

        SearchPipe.prototype.transform = function(pipeData, _a) {
            var pipeModifier = _a[0];
            return pipeData.filter(function(eachItem) {
                return eachItem['name'].toLowerCase().includes(pipeModifier.toLowerCase()) || eachItem['shortname'].toLowerCase().includes(pipeModifier.toLowerCase());
            });
        }