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

时间:2018-02-05 22:02:59

标签: mysql pivot-table

我有一个类似这样的表

+--------------------------+--------+------+---------+
|                          | 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的专家,无法从概念上看到我需要做什么。如果有人能给我任何指示,我将非常感激。谢谢。

1 个答案:

答案 0 :(得分:0)

您可以按多列进行分组:

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

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