Sql 如何计算妈妈和年环比?

Sql 如何计算妈妈和年环比?,sql,amazon-redshift,Sql,Amazon Redshift,我需要获取所有度量列的MoM和YoY值。 MoM列应具有上月值,与YoY的情况相同。 我可以用一个维度来做这件事,但是因为有很多维度,所以得到了错误的信息 以下是我为所有维度设置筛选器时正在运行的查询:- SELECT section,region,country,type,device,month,page_views, LAG(page_views, 1) OVER (ORDER BY month) as MoM, LAG(page_views, 12) OVER (ORDER BY mon

我需要获取所有度量列的MoM和YoY值。 MoM列应具有上月值,与YoY的情况相同。 我可以用一个维度来做这件事,但是因为有很多维度,所以得到了错误的信息

以下是我为所有维度设置筛选器时正在运行的查询:-

SELECT section,region,country,type,device,month,page_views,
LAG(page_views, 1) OVER (ORDER BY month) as MoM,
LAG(page_views, 12) OVER (ORDER BY month) as YoY
FROM table_name
Where region = 'RUCIS'
 and Country = 'Russia'
 and section ='METRICS' 
 and type_visits = 'All Visits'
 and device = 'Non Mobile Devices'
这很好,但如果我删除where条件,因为有很多地区和国家,在这种情况下,它不起作用

下面是一些示例数据


如何对所有维度执行此操作?

如果代码与
where
子句一起工作,但您希望它在没有子句的情况下工作,那么您可以使用
分区方式

SELECT section, region, country, type, device, month, page_views,
       LAG(page_views, 1) OVER (PARTITION BY section, region, country, type_visits, device
                                ORDER BY month) as MoM,
       LAG(page_views, 12) OVER (PARTITION BY section, region, country, type_visits, device
                                 ORDER BY month) as YoY
FROM table_name
WHERE region = 'RUCIS' and
      Country = 'Russia' and
      section ='METRICS' and
      type_visits = 'All Visits' and
      device = 'Non Mobile Devices';

您现在应该能够删除
WHERE
子句,或者根据您的需要调整它。

您确定此查询与mysql相关吗?mysql中没有OVER运算符。@Sharad。如果您的代码正常工作,那么它就不是MySQL。我删除了mysql标签。