首页 > 解决方案 > 如何计算一行与多行sql之间的差异

问题描述

我想计算sql中第一行与其他行之间的差异。我有一个名为“Trade”的表

日期 价格
2013-01-01 70
2013-01-02 71
2013-01-03 72
2013-02-01 73
2013-02-02 74
2013-02-03 75

预期输出:

日期 价格 第一个值
2013-01-01 70 无效的
2013-01-02 71 1
2013-01-03 72 2
2013-02-01 73 无效的
2013-02-02 74 1
2013-02-03 75 2

我使用了这个查询:

select date,
    price,
    ABS(first_value(price) over (partition by date_trunc('month', date)) - price)
from trades;

但我得到这个输出:

日期 价格 第一个值
2013-01-01 70 0
2013-01-02 71 1
2013-01-03 72 2
2013-02-01 73 0
2013-02-02 74 1
2013-02-03 75 2

标签: sql

解决方案


我会这样做 - 检查我们是否有一个月内的第一个值,如果有,那么null

select 
    date, 
    price, 
    case when month = first_value(month) over (partition by date_trunc('month', date))
        then null
        else ABS(first_value(price) over (partition by date_trunc('month', date)) - price) 
from trades;

推荐阅读