MySQL根据多种因素查找平均值

问题描述 投票:0回答:1

我有桌子做这样的事情

+--------------------------+--------+------+---------+
|                          | City   | Year | Density |
+--------------------------+--------+------+---------+
| Project 1                | City A | 2008 | 500     |
+--------------------------+--------+------+---------+
| Project 2                | City B | 2012 | 800     |
+--------------------------+--------+------+---------+
| Project 3                | City C | 2012 | 400     |
+--------------------------+--------+------+---------+
| Project 4                | City A | 2008 | 600     |
+--------------------------+--------+------+---------+
| Project 5                | City C | 2013 | 700     |
+--------------------------+--------+------+---------+
| etc (c. 30,000 projects spread across 30 cities)   |
+--------------------------+--------+------+---------+

(约30,000个项目分布在30个城市。)

我可以写一个像这样的查询:

SELECT Year, AVG(`Density`) as Density FROM table  where City=’A’ GROUP BY Year

哪个适用于一个城市。任何人都可以指出我正确的方向,我如何写一个单独的查询,计算每个城市的年平均值?我期待一个看起来像这样的结果表:

+------+--------+--------+--------+-------------+
|      | City A | City B | City C | City D, etc |
+------+--------+--------+--------+-------------+
| 2005 |        |        |        |             |
+------+--------+--------+--------+-------------+
| 2006 |        |        |        |             |
+------+--------+--------+--------+-------------+
| 2008 |        |        |        |             |
+------+--------+--------+--------+-------------+
| 2009 |        |        |        |             |
+------+--------+--------+--------+-------------+
| 2010 |        |        |        |             |
+------+--------+--------+--------+-------------+
| etc  |        |        |        |             |
+------+--------+--------+--------+-------------+

我试图在where子句(where in (select distinct City))中使用子查询,但是没有按照我的预期行事。

或者我只需要手动为30个城市中的每个城市单独划线?

我不是MySQL的专家,无法从概念上看到我需要做什么。如果有人能给我任何指示,我将非常感激。谢谢。

mysql pivot-table
1个回答
0
投票

您可以按多列分组:

SELECT city, year, AVG(density) AS density
FROM table
GROUP BY city, year

这将为每个城市/年份组合返回单独的行。要将城市作为列,您需要透视它。见MySQL pivot table

© www.soinside.com 2019 - 2024. All rights reserved.