如何从SELECT查询中获取最大值或最小值

时间:2019-04-11 10:12:22

标签: python sql postgresql select

我有一张桌子,上面有水表的读数。现在,该表每月将保存数百万条记录,我正在寻找一种方法,可以从当前电表读数中减去特定帐号的前一个电表读数,并获取相关时间段内消耗的单位

我设法为特定的account_number提取了最后两个条目,并尝试在选择查询中使用MAX或MIN,但似乎仅适用于列

这是我的代码

 SELECT (MAX(SELECT actual_reading FROM test_meter_readings
                        WHERE account_number = '23-456789T67'
                        ORDER BY timestamp_capture 
                        DESC
                        LIMIT 2)) - 
                    (MIN(SELECT actual_reading FROM test_meter_readings
                        WHERE account_number = '23-456789T67'
                        ORDER BY timestamp_capture 
                        DESC
                        LIMIT 2))
                      ''',)

我希望从表中的每个帐户获得的最后2个条目中获得差异

1 个答案:

答案 0 :(得分:0)

使用LAG()

select (actual_reading - prev_actual_reading) as diff
from (select tmr.*,
             lag(actual_reading) over (partition by account_number order by timestamp_capture) as prev_actual_reading
      from test_meter_readings tmr
      where account_number = '23-456789T67'
     ) tmr
order by timestamp_capture desc
fetch first 1 row only;  -- or limit 1

编辑:

要处理多个帐户,可以使用row_number()distinct on。第一种方法如下:

select (actual_reading - prev_actual_reading) as diff
from (select tmr.*,
             lag(actual_reading) over (partition by account_number order by timestamp_capture) as prev_actual_reading,
             row_number() over (partition by account_number order by timestamp_capture) as seqnum
      from test_meter_readings tmr
      -- where account_number = '23-456789T67'
     ) tmr
where seqnum = 1;