构建适当的 RANGE 子句

问题描述 投票:0回答:1

我有以下数据,我正在尝试获取上一年的利润:

> with tbl (year, country, product, profit) as (values (2000,'Finland', 'Computer', 1500), (2000, 'Finland', 'Phone', 100), (2001, 'Finland', 'Phone', 10), (2000, 'India', 'Calculator', 75), (2000, 'India', 'Calculator', 75), (2000, 'India', 'Computer', 1200)) 
  select country, year, profit, lag(profit) over (partition by country order by year) from tbl;
┌─────────┬──────┬────────┬─────────────────────────────────────────────────────────┐
│ country ┆ year ┆ profit ┆ lag(profit) OVER (PARTITION BY country ORDER BY "year") │
╞═════════╪══════╪════════╪═════════════════════════════════════════════════════════╡
│ India   ┆ 2000 ┆     75 ┆                                                         │
│ India   ┆ 2000 ┆     75 ┆                                                      75 │
│ India   ┆ 2000 ┆   1200 ┆                                                      75 │
│ Finland ┆ 2000 ┆   1500 ┆                                                         │
│ Finland ┆ 2000 ┆    100 ┆                                                    1500 │
│ Finland ┆ 2001 ┆     10 ┆                                                     100 │
└─────────┴──────┴────────┴─────────────────────────────────────────────────────────┘

但是,这似乎只是获得了前一行,而不是我想要的,即获得该国家上一年的利润值的

LAG
。预期结果应该是:

┌─────────┬──────┬────────┬─────────────────────────────────────────────────────────┐
│ country ┆ year ┆ profit ┆ 
╞═════════╪══════╪════════╪═════════════════════════════════════════════════════════╡
│ India   ┆ 2000 ┆     75 ┆                                                         │
│ India   ┆ 2000 ┆     75 ┆                                                         │
│ India   ┆ 2000 ┆   1200 ┆                                                         │
│ Finland ┆ 2000 ┆   1500 ┆                                                         │
│ Finland ┆ 2000 ┆    100 ┆                                                         │
│ Finland ┆ 2001 ┆     10 ┆                                                  1600   │
└─────────┴──────┴────────┴─────────────────────────────────────────────────────────┘

自2001年芬兰以来,这是唯一一个同时拥有同一国家上一年记录的记录。实现此目的正确的

RANGE
子句是什么? (Postgres 的 BigQuery 都可以用于测试目的)。

sql postgresql google-bigquery window-functions
1个回答
0
投票

您需要先按国家和年份汇总利润,然后才能使用 LAG 功能。以下内容适用于 SQL Server,但如果 PostgreSQL 不允许此语法,您可以在 CTE 或子查询中求和和分组,然后添加“主”查询以添加 LAG 函数。

select 
   country
 , year
 , sum(profit) as ProfitThisYear
 , lag(sum(profit)) over (partition by country order by year) as ProfitLastYear
from tbl 
group by 
  country
, year

© www.soinside.com 2019 - 2024. All rights reserved.