具有复杂查询的预制列上的 sql sum 或聚合函数
我有一个查询,需要在很长一段时间内获取一周 7 天的平均数据(价格)。周一、周二等的 IE 平均价格。它工作正常,但我不确定如何在同一个查询中求和该查询找到的平均价格?求和第 1 天..第 5 天
按照目前的情况,此查询对所有价格的全部求和...即巨大的数字..不是来自平均值。
有什么想法吗?顺便说一句,这是来自 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是应该有用的东西......
注意我没有测试,所以可能有拼写错误。
Here is something that should work....
note I did not test so there might be typos.