我有一个以下格式的表格 -
region country revenue datetime
apac japan 1000 2002-01-01
apac china 2000 2001-02-01
apac japan 1500 2001-01-01
apac china 3000 2002-02-01
emea germany 4000 2003-04-01
emea france 5000 2004-09-01
emea germany 2000 2004-04-01
emea france 6000 2005-09-01
我正在尝试编写一个查询,该查询会给出每个地区和县的月度增长
我在postgres中使用datetrunc('month',datetime)和lag()函数来获取之前的值,但无法按区域和国家/地区进行分组 - 当我这样做时,表格的粒度会发生变化而且我没有得到所需的输出。
以下是查询 -
select region,
country,
date_trunc('month',datetime) as datum,
sum(revenue),
round(1.0-(cast(revenue as NUMERIC)/lag(revenue,1) OVER())*100,1)
from mytable
GROUP BY datum,region,country,revenue
ORDER BY datum ASC;
答案 0 :(得分:1)
您需要partition by
:
select region, country,
date_trunc('month', datetime) as datum,
sum(revenue),
round(1.0-(cast(revenue as NUMERIC)/lag(sum(revenue), 1) over (partition by region, country order by date_trunc('month',datetime)))*100,1)
from mytable
group by datum, region, country
order by datum asc;
此外,revenue
不应该在group by
。
或者,首先进行聚合更容易表达:
select region, county, datum, rev,
lag(rev) over (partition by region, country order by datum) as prev_rev
from (select region, country,
date_trunc('month', datetime) as datum,
sum(revenue) as rev
from mytable
group by datum, region, country
) drc
order by datum asc;