计算来自多年的数据和按位置分组

时间:2013-06-11 00:58:54

标签: mysql

我想制作一些有关某些地区人口的图表, 这是我的表的一个例子;

mmr                              mmrp
+-------+--------+--------+     +-------+------------+
| rm    |city    |region  |     | rm    | date       |
+-------+--------+--------+     +-------+------------+
| 123   |city_a  |region1 |     | 123   | 2012-xx-xx |
| 124   |city_a  |region1 |     | 124   | 2013-xx-xx |
| 210   |city_b  |region1 |     | 210   | 2012-xx-xx |
| 211   |city_c  |region2 |     | 211   | 2011-xx-xx |
| 212   |city_d  |region3 |     | 212   | 2011-xx-xx |
| 213   |city_e  |region3 |     | 213   | 2013-xx-xx |
+-------+--------+--------+     +-------+------------+

我想计算区域1中按城市划分的人数,以及人员<区域外1>按地区划分 3年内 ,这就是我想要实现的目标;

+-------+--------+--------+--------+
| area  | 2011   | 2012   | 2013   |
+-------+--------+--------+--------+
|city_a | 0      | 1      | 1      |
|city_b | 0      | 1      | 0      |
|region2| 1      | 0      | 0      |
|region3| 1      | 0      | 1      |
+-------+--------+--------+--------+

到目前为止,我只知道如何计算特定的区域 ,这就是我所做的;

SELECT a.city, count(b.rm) as 2013
FROM mmr a join mrpp b on (a.rm=b.rm)
where year(b.date) = 2013 and a.region like 'region1' GROUP BY city

但它只显示2013年来自region1的数量,有没有办法实现呢?

2 个答案:

答案 0 :(得分:1)

SELECT IF(a.region = 'region1', city, region) AS area,
       SUM(year(b.date) = 2011) AS `2011`,
       SUM(year(b.date) = 2012) AS `2012`,
       SUM(year(b.date) = 2013) AS `2013`
FROM mmr a JOIN mrpp b ON a.rm = b.rm
WHERE b.date >= `2011-01-01`
GROUP BY area

答案 1 :(得分:0)

SELECT a.city area, sum(if(year(b.date)=2011,1,0) as 2011,
 sum(if(year(b.date)=2012,1,0) as 2012,
 sum(if(year(b.date)=2013,1,0) as 2013
FROM mmr a join mrpp b on (a.rm=b.rm)
where year(b.date) between 2011 and 2013
and a.region = 'region1' 
GROUP BY city

union

SELECT a.region area, sum(if(year(b.date)=2011,1,0) as 2011,
 sum(if(year(b.date)=2012,1,0) as 2012,
 sum(if(year(b.date)=2013,1,0) as 2013
FROM mmr a join mrpp b on (a.rm=b.rm)
where year(b.date) between 2011 and 2013
and a.region <> 'region1'
GROUP BY a.region