views:

278

answers:

1

I have a query that takes avg data (prices) from 7 days of the week for a long interval. IE avg prices for monday, tues, etc. It works fine, but I'm unsure how I can in the same query sum the avgs that this query finds? Summing Day1..Day5

As it stands this query sums the entire from of all the prices... IE huge number.. not from the avg.

Any ideas? BTW this is from Postgres... Thanks

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  A: 

Here is something that should work....

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
)

note I did not test so there might be typos.

Hogan