[英]Calculate the difference between the max value of a row and other rows based on the date
[英]Hive Query : To calculate max indicator value based on priority and date
我試圖構架查詢,但不知何故因此無法獲得所需的結果。 我是新來的。 道歉,如果很簡單。
源數據:
Ik - priority - ind1 - ind2 - date
1 - A - y - n - 2009/01/01
1 - B - n - y - 2019/02/09
1 - C - null - (empty)- 2018/05/07
2 - A - null - y - 2005/02/02
2 - B - null - y - 2006/05/05
2 - C - n - null - 2018/01/01
問題陳述
根據優先級和日期,我們將需要為每個ik填充指標值(ind1和ind2)。
輸出表格式
Ik,ind1,ind2
邏輯是
在此分組依據將在ik字段上完成。 因此,對於上述數據集,在輸出中將僅填充單個記錄。
如果對於相同的ik值,優先級為A且指示標志(ind1,ind2)為y值,則輸出應填充為“ y”。
但是,如果ik相同,則優先級為A,但指標的值不為“ y”。 (可能的值為null,n,空字符串)
然后將根據BC優先級基於日期字段(按日期排序-按ik的最新記錄)選擇最新指標。
以上數據集的輸出為
Ik - ind1 - ind2
1 - y - y
2 - n - y
這里ind1是max(ind1)。 我能夠得出。 但是無法導出ind2。
您能幫我創建查詢嗎?
測試數據: http : //demo.gethue.com/hue/editor?editor=293916
with your_table as -------use your table instead of this subquery
(
select stack(6,
1 ,'A', 'y','n', '2009/01/01',
1 ,'B', 'n','y', '2019/02/09',
1 ,'C', null,'' , '2018/05/07',
2 ,'A', null,'y', '2005/02/02',
2 ,'B', null,'y', '2006/05/05',
2 ,'C', 'n', null, '2018/01/01'
) as (Ik, priority, ind1, ind2, date)
) -------use your table instead of this subquery
select ik,
max(case when priority ='A' and ind1='y' then 'y' else last_ind1 end) ind1,
max(case when priority ='A' and ind2='y' then 'y' else last_ind2 end) ind2
from
(
select Ik, priority, ind1, ind2, date,
last_value(ind1) over (partition by Ik order by date) last_ind1,
last_value(ind2) over (partition by Ik order by date) last_ind2
from your_table -------use your table instead
)s
group by ik;
結果:
ik ind1 ind2
1 y y
2 n y
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.