【问题标题】:PostgreSQL Percent Change using Row Number使用行号的 PostgreSQL 百分比变化
【发布时间】:2020-07-26 06:17:25
【问题描述】:

我正在尝试使用 PostgreSQL 的行号来查找百分比变化,但我遇到了一个错误,我的“percent_change”列显示为 0。

这是我的代码。

WITH CTE AS (
SELECT date, sales, ROW_NUMBER() OVER (ORDER by date) AS rn
FROM sales_2019)

SELECT c1.date, c1.sales,
CAST(COALESCE (((c1.sales - c2.sales) * 1.0 / c2.sales) * 100, 0) AS INT) AS percent_change
FROM CTE AS c1
LEFT JOIN CTE AS c2 
ON c1.date = c2.date AND c1.rn = c2.rn + 1

这是我的SQL table,以备不时之需。提前谢谢你,非常感谢。

【问题讨论】:

  • 你期待什么输出?
  • 我期待的输出是这样的:pastebin.com/42RwSxkP
  • 你可以查看答案
  • 您正在将值转换为整数。预计会发生什么?

标签: sql postgresql window-functions


【解决方案1】:

您可以使用 LAG() 来满足您的要求:

select 
date, 
sales, 
round(coalesce((((sales-(lag(sales) over (order by date)))*1.0)/(lag(sales) over (order by date)))*100,0),2)
                                                            
from sales_2019

或者你可以试试WITH 子句

with cte as ( select
  date,
  sales,
  coalesce(lag(sales) over (order by date),0) as previous_month
                            from sales_2019
  )
select 
date,
sales,
round( coalesce( (sales-previous_month)*1.0/nullif(previous_month,0),0 )*100,2)
from cte
           

DEMO

根据评论中的要求进行编辑

with cte as ( select
  date_,
  sales,
  ROW_NUMBER() OVER (ORDER by date_) AS rn1,
  ROW_NUMBER() OVER (ORDER by date_)-1 AS rn2
                            from sales_2019
  )
  
  select t1.date_,
  t1.sales,
  round( coalesce( (t1.sales-t2.sales)*1.0/nullif(t2.sales,0),0 )*100,2)
  from cte t1 left join cte t2 on t1.rn2=t2.rn1

DEMO

【讨论】:

  • 谢谢!!是否可以使用 row_number() 函数来做到这一点?我只是问,因为我喜欢有一个 lag() 函数的替代品,所以我可以同时使用。
  • 我很难理解为什么我们需要使用 coalesce 和 nullif。我在网上查了定义,但我很困惑。是否可以使用行号在不合并和 nullif 的情况下编写查询以获取百分比变化?
  • @Kay 最好用一些示例数据提出一个单独的问题。 AFA coalescenullif 它们是非常直接的 SQL 函数,有目的。你在哪里感到困惑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
  • 2020-07-14
相关资源
最近更新 更多