簡體   English   中英

Hive 滯后窗口分區

[英]Hive lag window partition

這是我的表:

sensor_name, ext_value, int_value, growth
47ACXVMACSENS01, 238, 157, 1
47ACXVMACSENS01, 157, 256, 2
47ACXVMACSENS01, 895, 345, 3
47ACXVMACSENS01, 79, 861, 3
91DKCVMACSENS02, 904, 858, 1
91DKCVMACSENS02, 925, 588, 1
91DKCVMACSENS02, 15, 738, 1
91DKCVMACSENS02, 77, 38, 2

前 3 列(sensor_name、ext_value、int_value)是給定的數據,第 4 列是我想要的計算列,這個增長列基於每組 sensor_name 的列(ext_value、int_value)的值。

增長列的結果計算如下:對於每組sensor_name,將每行的int_value與前一行的ext_value進行比較,如果沒有前一行則其ext_value為0,如果當前行的int_value為高於前一行的 ext_value 則增長值增加 1。如果當前的 int_value 低於前一行的 ext_value 則增長保持與之前增長值相同的值。

在上面的例子中,

for the very first row, 157 is compared with the previous row ext_value that doesn't exist so it's 0, 
157 > 0 then growth value increase of 1 from 0.
on the 2nd row, 256 > 238 then growth = 1+1=2
on the 3rd row, 345 > 159 then growth = 2+1=3
on the 4th row, 861 < 895 then growth remains at the same previous value, so 3.

then the logic is re-applied to the second set of sensor_name :
1st row, 858 > 0 (because there is now previous row for this sensor_name) then growth = 1
2nd row, 588 < 904 then growth = 1
3rd row, 738 < 925 then growth = 1
4th row, 38 > 15 then growth = 1+1=2

我已經嘗試在 sensor_name 分區上使用滯后窗口,但直到現在它才給我正確的結果。

我該如何解決這個問題?

使用lag得到之前的ext_value,計算growth flag並使用running count來計算growth。 正如您在評論中所說,我添加了 rcv_time 列:

with your_table as ( --use your table instead of this
select stack(8,
'47ACXVMACSENS01', 238, 157, '2019-11-01 10:10:01',
'47ACXVMACSENS01', 157, 256, '2019-11-01 10:10:02',
'47ACXVMACSENS01', 895, 345, '2019-11-01 10:10:03',
'47ACXVMACSENS01', 79, 861,  '2019-11-01 10:10:04',
'91DKCVMACSENS02', 904, 858, '2019-11-01 10:10:05',
'91DKCVMACSENS02', 925, 588, '2019-11-01 10:10:06',
'91DKCVMACSENS02', 15, 738,  '2019-11-01 10:10:07',
'91DKCVMACSENS02', 77, 38,  '2019-11-01 10:10:08'
) as (sensor_name, ext_value, int_value, rcv_time )
)

select sensor_name, ext_value, int_value, 
       count(case when int_value>prev_ext_value then true end) over(partition by sensor_name order by rcv_time) growth
from
(
select sensor_name, ext_value, int_value, rcv_time, 
       lag(ext_value,1,0) over(partition by sensor_name order by rcv_time) prev_ext_value
  from your_table
)s; 

結果:

47ACXVMACSENS01 238     157     1
47ACXVMACSENS01 157     256     2
47ACXVMACSENS01 895     345     3
47ACXVMACSENS01 79      861     3
91DKCVMACSENS02 904     858     1
91DKCVMACSENS02 925     588     1
91DKCVMACSENS02 15      738     1
91DKCVMACSENS02 77      38      2

產生的結果與您的示例完全相同

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM