[英]How to get max of column based on grouping by date column in postgreSQL
第一次在這里發布海報,不確定我的標題是否真的概述了我在這里尋找的內容......
我正在嘗試獲得以下信息:
“一年中,每種房產類型的平均收入最高是哪一個月?”
我有兩個表,其中包含我正在使用的以下字段:
calendar_metric
period (this is a date, formatted 'yyyy-mm-dd'
revenue
airbnb_property_id
property
property_type
airbnb_property_id
我已經想出了如何顯示月份、屬性類型和平均收入,但我認為在正確分組時遇到了麻煩。
select
extract(month from calendar_metric.period) as month,
property.property_type,
avg(calendar_metric.revenue) as average_revenue
from
calendar_metric
inner join property on
calendar_metric.airbnb_property_id = property.airbnb_property_id
group by
month,
property_type
我想要它 output 看起來像這樣:
month | property_type | max_average_revenue
---------------------------------------------
1 | place | 123
2 | floor apt | 535
3 | hostel | 666
4 | b&b | 363
5 | boat | 777
etc| etc | etc
但目前我得到了這個:
month-property_type | max_average_revenue
---------------------------------------------
1 | place | 123
2 | floor apt | 535
1 | place | 444
4 | b&b | 363
4 | b&b | 777
etc| etc | etc
所以基本上,當我從日期戳中提取月份時,月份會重復回來,數據集跨越 5 年左右,並且可能沒有分組對嗎? 我知道我可能遺漏了一些簡單的東西,我似乎無法弄清楚如何正確地做到這一點。
幫助!
您應該按year-month
grouping
,因為您正在嘗試查看5 year
期間。
select
extract(month from calendar_metric.period) as month,
property.property_type,
avg(calendar_metric.revenue) as average_revenue
from
calendar_metric
inner join property on
calendar_metric.airbnb_property_id = property.airbnb_property_id
group by
extract(year from period),
month,
property_type
我認為您的查詢基本上就在那里,它只是返回所有月份,而不僅僅是過濾掉您不想要的行。 對於這類事情,我傾向於使用DISTINCT ON
子句,例如:
SELECT DISTINCT ON (property_type)
p.property_type, extract(month from cm.period) AS month,
avg(cm.revenue) AS revenue
FROM calendar_metric AS cm
JOIN property AS p USING (airbnb_property_id)
GROUP BY property_type, month
ORDER BY property_type, revenue DESC;
我已經將您的查詢縮短了一點,希望它對您仍然有意義。
使用 CTE,您可以分兩步表達這一點,這可能更容易理解正在發生的事情:
WITH results AS (
SELECT p.property_type, extract(month from cm.period) AS month,
avg(cm.revenue) AS revenue
FROM calendar_metric AS cm
JOIN property AS p USING (airbnb_property_id)
GROUP BY property_type, month
)
SELECT DISTINCT ON (property_type)
property_type, month, revenue
FROM results
ORDER BY property_type, revenue DESC;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.