2009-12-02 40 views
0

我有一個查詢需要從一週的7天內獲取平均數據(價格)很長的時間間隔。 IE的平均價格爲星期一,tues等。它工作正常,但我不確定如何在同一個查詢中總結此查詢發現的平均值?總結Day1..Day5複雜查詢的預fab列上的sql總結或聚合函數

因爲它站立此查詢總和從所有的價格... IE瀏覽器巨大的數字..不是從平均。

任何想法?順便說一句,這是從Postgres的...謝謝

SELECT rooms.name, rooms.id, 
MAX(CASE WHEN (EXTRACT(DOW FROM availables.bookdate) - EXTRACT(DOW FROM DATE '2009-12-13')) = 0 THEN (availables.price) ELSE 0 END) AS day1, 
MAX(CASE WHEN (EXTRACT(DOW FROM availables.bookdate) - EXTRACT(DOW FROM DATE '2009-12-13')) = 1 THEN (availables.price) ELSE 0 END) AS day2, 
MAX(CASE WHEN (EXTRACT(DOW FROM availables.bookdate) - EXTRACT(DOW FROM DATE '2009-12-13')) = 2 THEN (availables.price) ELSE 0 END) AS day3, 
MAX(CASE WHEN (EXTRACT(DOW FROM availables.bookdate) - EXTRACT(DOW FROM DATE '2009-12-13')) = 3 THEN (availables.price) ELSE 0 END) AS day4, 
MAX(CASE WHEN (EXTRACT(DOW FROM availables.bookdate) - EXTRACT(DOW FROM DATE '2009-12-13')) = 4 THEN (availables.price) ELSE 0 END) AS day5, 
(AVG(availables.price)) AS avg, 
(SUM(availables.price)) AS sum, MAX((SIGN(spots)-1) + 1) AS beds 
FROM availables 
INNER JOIN rooms 
ON availables.room_id=rooms.id 
WHERE availables.room_id = '1780' AND availables.price > 0 
GROUP BY rooms.id, rooms.name 

回答

1

這是應該工作....

select avg(mon+tues+weds+thur+fri) as averageall, 
     sum(mon+tues+weds+thur+fri) as sumall, 
    avg(mon) as avgmon, 
    avg(tues) as avgtues, 
    avg(weds) as avgweds, 
    avg(thurs) as avgthurs, 
    agv(fri) as avgfri, 
MAX((SIGN(spots)-1) + 1) AS beds 
from 
(
SELECT rooms.name, rooms.id, 
CASE WHEN EXTRACT(DOW FROM availables.bookdate) = 1 THEN (availables.price) ELSE 0 END) AS mon, 
CASE WHEN EXTRACT(DOW FROM availables.bookdate) = 2 THEN (availables.price) ELSE 0 END) AS tues, 
CASE WHEN EXTRACT(DOW FROM availables.bookdate) = 3 THEN (availables.price) ELSE 0 END) AS weds, 
CASE WHEN EXTRACT(DOW FROM availables.bookdate) = 4 THEN (availables.price) ELSE 0 END) AS thur, 
CASE WHEN EXTRACT(DOW FROM availables.bookdate) = 5 THEN (availables.price) ELSE 0 END) AS fri, 
spots, rooms.id, rooms.name 
FROM availables 
INNER JOIN rooms 
ON availables.room_id=rooms.id 
WHERE availables.room_id = '1780' AND availables.price > 0 
) 
GROUP BY rooms.id, rooms.name 
) 

注意到我沒有測試所以有可能是拼寫錯誤。