2016-08-24 70 views
0

我有一个sql查询将返回特定年份的给定属性类型的平均售价。SQL获取多年的平均销售成本

SELECT 
      `table`.Property AS 'Property', 
      `table`.Year AS 'Year', 
      AVG(`table`.`Value`) AS 'Average Sold Price' 
      FROM 
      `table` 
      WHERE `table`.`Area` LIKE '%NW1%' 
      AND `table`.`Property` LIKE '%F%' 
      AND `table`.`Year` = '2011' 
      GROUP BY `table`.Property,`table`.Year 
      ORDER BY 
      `table`.Property ASC 

输出看起来像这样

| Property | Year | Average Sold Price 
| F  | 2011 | 440242.18137204903 

上在2016

| Property | Year | Average Sold Price 
| F  | 2016 | 702453.9544754727 

查找 - 我将如何改变查询得到一个合并后的输出 - 所以这样的事情,尽量减少通话次数等。

| Property | Average Sold Price (2011) | Average Sold Price (2016) 
| F  | 440242.18137204903  | 702453.9544754727 
+0

这将是慢得它作为一个行,但如果去掉'AND table.year ='2011''你会得到多行 – Cfreak

+0

您所需要的功能都年是一个拐点 - HTTP: //stackoverflow.com/questions/7674786/mysql-pivot-table –

+2

WHERE year IN(2011,1016)GROUP BY year ...如前所述,处理表示层中的显示问题 – Strawberry

回答

0
SELECT 
      `table`.Property AS 'Property', 
      `table`.Year AS 'Year', 
      AVG(`table`.`Value`) AS 'Average Sold Price' 
      FROM `table` 
      WHERE `table`.`Area` LIKE '%NW1%' 
      AND `table`.`Property` LIKE '%F%' 
      AND `table`.`Year` IN(2011,2016) 
      GROUP BY `table`.Property,`table`.Year 
      ORDER BY `table`.Property ASC 

^这产生了一个可用的输出。

| Property | Year | Average Sold Price 
| F  | 2011 | 440242.18137204903 
| F  | 2016 | 702453.9544754727