2016-08-24 74 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