我的 LAG 函数没有按预期工作 MySQL 8.x

My LAG function not working as expected MySQL 8.x

我的 table 看起来像这样:

metro_region,值,日期

11 月份有多个值(每个日期一个)。大约有 100 个都市区。

我希望我的报告包含以下数据:

Metro_region  Today  Yesterday  2daysAgo  3dayAgo
MetroRegionA   40.1    54.3       64.8     48.1
MetroRegionB   31.1    53.1       97.8     43.2

我尝试了什么:

select 
  metro_region, 
  date,
  LAG(value,3) over (Partition by metro order by metro) as "3daysAgo", 
  LAG(value,2) over (Partition by metro order by metro) as "2daysAgo", 
  LAG(value,1) over (Partition by metro order by metro) as "Yesterday", 
  value as Today
from mytable 
where date = curdate();

我怀疑我没有正确分区...或者只是严重遗漏了如何使用 LAG...任何见解都将受到赞赏!

您需要今天和过去 3 天的结果,所以您不能只过滤今天。
先获取 4 天的结果,然后筛选今天的结果。
此外,在每个分区中,您必须按 date 而不是 metro:

排序
select metro_region, date, `3daysAgo`, `2daysAgo`, `Yesterday`, Today
from (
  select metro_region, 
         date, 
         LAG(value,3) over (partition by metro_region order by date) as `3daysAgo`, 
         LAG(value,2) over (partition by metro_region order by date) as `2daysAgo`, 
         LAG(value,1) over (partition by metro_region order by date) as `Yesterday`, 
         value as Today 
  from mytable 
  where date between curdate() - interval 3 day and curdate()
) t
where date = curdate()

查看简化版 demo