sql—配置单元中两个记录之间的差异

5vf7fwbs  于 2021-05-29  发布在  Hadoop
关注(0)|答案(2)|浏览(397)

我有一个有5列的表,我需要找到前两个记录的count列之差。我可以根据某些条件获得前两名的记录。例子,
我的table看起来像:

name address count current_date_time
john LA      102    2019-07-12 12:24:38
peter MAC    105    2019-07-12 12:24:40
john  NY      210   2019-07-12 12:24:02
john  WD      18    2019-07-12 12:24:12

选择查询以获取前两行:

SELECT count 
FROM table_name 
WHERE name="john" 
ORDER BY current_date_time DESC LIMIT 2

结果是:

count
102
18

但我需要102和18之间的差值。
如何编写子查询?

odopli94

odopli941#

使用超前或滞后分析函数来处理按某列排序的上一行/下一行:
例如:

with your_data as (
select stack(4,
'john'  ,'LA'  ,   102, '2019-07-12 12:24:38',
'peter' ,'MAC' ,   105, '2019-07-12 12:24:40',
'john'  ,'NY'  ,   210, '2019-07-12 12:24:02',
'john'  ,'WD'  ,   18 , '2019-07-12 12:24:12'
) as (name, address, count, current_date_time)
)

select prev_count-count from
(
select s.*, lag(count) over(partition by name order by current_date_time) prev_count,
       row_number() over(partition by name order by current_date_time desc) rn
  from your_data s 
  where name="john" 
)s where rn=2;

退货:

OK
192
wydwbb8l

wydwbb8l2#

应用 lead() 窗口解析函数来确定下一行的列值。

SELECT count - ld as "Difference"
  FROM
 (
  SELECT count, lead(count,1,0) over (order by current_date_time desc ) as ld,
         current_date_time 
    FROM table_name 
   WHERE name="john" 
  ORDER BY current_date_time DESC LIMIT 2
 ) q
ORDER BY q.current_date_time DESC LIMIT 1

去哪儿
lead(count,1,0) 1 表示偏移,即。 1 排在后面,然后 0 表示默认值。
postgres演示( hive 也有类似的语法)

相关问题