将两个聚合查询合并到一个视图中
问题描述:
我无法围绕此视图围绕我的大脑。我有两个疑问,我使用的定期报告:将两个聚合查询合并到一个视图中
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)
答
你需要连接两个查询作为表像下面
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
答
...在评论看起来像废话:)
由于SQL查询再次,我想出的查询看起来像:
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
非常好!非常感谢你。 我*只是*在使用更多的google搜索之后提出了一些非常相似的东西。我看起来像:'select * from (select year(a.creation)as year,count(*)as'year built' 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 ' 感谢您的回应。我很感激! – dkoleary