如何在MySQL中进行avg和多个分组?

时间:2014-10-01 16:55:14

标签: php mysql

我有一个价值很高的付费数据库,有超过300万条记录。

我需要计算每年按房产类型支付的平均价格

我的数据库结构如下:

Date                  Price               Type               Post Code

2014-01-20 00:00      2260000             D                  L23 8TY 
2011-02-19 00:00      2015445             D                  CH44 4RT 
2012-01-20 00:00      1460000             S                  SE2 5hy   

(D = Detached,s = Semi detched by the way,依此类推......)

现在我有以下查询,它计算每年所有属性的平均值,这是正常的,

SELECT AVG(Price) AS AvgPrice, left(Date,4) AS Year, Type FROM PricePaid WHERE PostCode LIKE'L17%' 
AND left(Date,4) >= 2009 AND left(Date,4) <= 2014 
GROUP BY Year

此输出

AvgPrice         Year

160,671          2009 
168,393          2010 
161,283          2011 
166,623          2012 
172,111          2013 
177,608          2014 

但是我需要输出这样的东西:

AvgPrice         Year       DAverage       SAverage    

160,671          2009           ?              ?
168,393          2010           ?              ?
161,283          2011 
166,623          2012 
172,111          2013 
177,608          2014 

我有一种感觉,我需要使用某种if语句并计算如下:

SELECT AVG(Price) AS AvgPrice, left(Date,4) AS Year, Type FROM PricePaid WHERE PostCode LIKE'L17%' 
AND left(Date,4) >= 2009 AND left(Date,4) <= 2014

IF (Type = 'D', AVG(Price) AS DAvgPrice ),
IF (Type = 'S', AVG(Price) AS SAvgPrice ),

GROUP BY Year

但这比我的技能允许更多,任何人都可以指出我正确的方向。提前感谢你的人。

0 个答案:

没有答案