我正在努力與MySQL的聲明,並希望有一些指導,因爲我很接近,但不是那裏。我有一個數據庫,其中包含一個物業地址表和房產租賃列表。物業地址與一個或多個地區有關,這些地區與地區表有關,然後與郊區表相關。MySQL AVG和分組
我想創建一個結果,該結果給出了每個月每個郊區的平均租金以及臥室的數量。
例如:
District Suburb Month YEAR YMD Bedrooms DataAverage Nelson The Brook 01 2012 2012-01-01 00:00 1 190 Nelson The Brook 01 2012 2012-01-01 00:00 2 274 Nelson The Brook 01 2012 2012-01-01 00:00 3 341
,我可以再轉換成表格如下:
Average Rent
Beds by Suburb Jan-12 Feb-12 Mar-12 Apr-12 May-12 Jun-12 Jul-12 The Brook 1 $150 $245 $160 $285 $135 $370 $350 2 $330 $340 $380 $310 $335 $345 $355 3 $350 $380 $310 $395 $380 $350 $350 Inner City 1 $160 $245 $260 $285 $295 $300 $350 2 $360 $440 $480 $410 $535 $545 $555 3 $370 $480 $510 $595 $480 $450 $550
我目前的SQL查詢是這樣的:
SELECT d.name as District, s.name AS Suburb,
FROM_UNIXTIME(l.StartDate,'%m') AS Month,
FROM_UNIXTIME(l.StartDate,'%Y') AS YEAR,
FROM_UNIXTIME(l.StartDate, '%Y-%m-01 00:00') AS YMD,
p.Bedrooms,
REPLACE(FORMAT(AVG(l.RentPerWeek),0),',','') AS DataAverage
FROM properties p
LEFT JOIN listings l on l.property_id=p.id
LEFT JOIN regions r on p.region_id=r.id
LEFT JOIN districts d on d.region_id=r.id
LEFT JOIN suburbs s on s.district_id=d.id
WHERE FROM_UNIXTIME(l.StartDate) BETWEEN DATE(NOW()) - INTERVAL (DAY(NOW()) - 1) DAY - INTERVAL 11 MONTH AND NOW()
GROUP BY District, Suburb, Year, Month, Bedrooms
ORDER BY District, Suburb ASC, YMD ASC, Bedrooms ASC
不幸的是我每個郊區都會得到同樣的結果。我想我可能需要創建一個子查詢SQL語句才能正常工作,但我不完全確定。
所以我得到的東西是這樣的:
District Suburb Month YEAR YMD Bedrooms DataAverage Nelson The Brook 01 2012 2012-01-01 00:00 1 190 Nelson The Brook 01 2012 2012-01-01 00:00 2 330 Nelson The Brook 01 2012 2012-01-01 00:00 3 350 Nelson The Brook 02 2012 2012-02-01 00:00 1 245 Nelson The Brook 02 2012 2012-02-01 00:00 2 340 Nelson The Brook 02 2012 2012-02-01 00:00 3 380 ... Nelson Inner City 01 2012 2012-01-01 00:00 1 190 Nelson Inner City 01 2012 2012-01-01 00:00 2 330 Nelson Inner City 01 2012 2012-01-01 00:00 3 350 Nelson Inner City 02 2012 2012-02-01 00:00 1 245 Nelson Inner City 02 2012 2012-02-01 00:00 2 340 Nelson Inner City 02 2012 2012-02-01 00:00 3 380 .etc.
Average Rent
Beds by Suburb Jan-12 Feb-12 Mar-12 Apr-12 May-12 Jun-12 Jul-12 The Brook 1 $150 $245 $160 $285 $135 $370 $350 2 $330 $340 $380 $310 $335 $345 $355 3 $350 $380 $310 $395 $380 $350 $350 Inner City 1 $150 $245 $160 $285 $135 $370 $350 2 $330 $340 $380 $310 $335 $345 $355 3 $350 $380 $310 $395 $380 $350 $350
任何指針或協助將不勝感激。
啊....蛋面上...我已經有一個suburb_id列。我不知道爲什麼我沒有使用????感謝您幫助我找到在樹林裏的阿甘... – Greg