将两个聚合查询合并到一个视图中

时间:2017-04-07 15:13:59

标签: mysql group-by

我无法围绕这一个缠绕我的大脑。我有两个用于定期报告的查询:

mysql> select year(a.creation) as year, count(*) as 'built by year'
    -> from hosts a
    -> where year(a.creation) > 2013
    -> group by year(a.creation);
+------+---------------+
| year | built by year |
+------+---------------+
| 2014 |           372 |
| 2015 |          1115 |
| 2016 |           779 |
| 2017 |           268 |
+------+---------------+
4 rows in set (0.00 sec)

mysql> select year(b.decom) as year, count(*) as 'decomed by year'
    -> from hosts b
    -> where year(b.decom) > 2013
    -> group by year(b.decom);
+------+-----------------+
| year | decomed by year |
+------+-----------------+
| 2015 |              68 |
| 2016 |             816 |
| 2017 |              27 |
+------+-----------------+
3 rows in set (0.00 sec)

我希望能够在一个视图中报告这两种情况。

我已经尝试了一些事情,但最近的我来了一个很好的笛卡尔联盟。幸运的是,db很小:

mysql> select year(a.creation) as year, count(a.hostname) as 'built by year', count(b.hostname) as 'decomed by year'
    -> from hosts a
    ->   left join hosts b on year(a.creation) = year(b.decom)
    -> where year(a.creation) > 2013 group by year(a.creation), year(b.decom);
+------+---------------+-----------------+
| year | built by year | decomed by year |
+------+---------------+-----------------+
| 2014 |           372 |               0 |
| 2015 |         75820 |           75820 |
| 2016 |        635664 |          635664 |
| 2017 |          7236 |            7236 |
+------+---------------+-----------------+
4 rows in set (3.59 sec)

2 个答案:

答案 0 :(得分:1)

再次感谢,我提出的查询看起来像:

select * from
(select year(a.creation) as year, count(*) as 'built by year'
from hosts a
where year(a.creation) > 2013
group by year(a.creation)
) x left join
( select year(decom) as year, count(b.hostname) as 'decomed by year'
from hosts b
where year(b.decom) > 2013
group by year(b.decom)
) y
on x.year = y.year

答案 1 :(得分:0)

您需要将两个查询加入如下表

  selecgt a.year,a.built_by_year,b.decomed_by_year from(
                  select year(a.creation) as year, count(*) as 'built_by_year'
                  from hosts a
                  where year(a.creation) > 2013
                  group by year(a.creation)
                 ) a
            left join (
                 select year(b.decom) as year, count(*) as 'decomed_by_year'
                 from hosts b
                 where year(b.decom) > 2013
                 group by year(b.decom)
               ) b
              on a.year=b.year