我有如下表格:
itm numbr
1 2
11 21
NULL 31
12 41
NULL 51
13 61
我想用itm,numbr和额外的列输出,如下所述:
itm numbr incr
1 2 1
11 21 1
NULL 31 2
12 41 2
NULL 51 3
13 61 3
只有当ITM等于NULL时,incr才应增加其值,否则它应显示与先前值相同的值。
1。 我尝试过row_sequence
select itm,numbr,row_sequence() as incr from tablename;
但显示1,2,3,4,5,6。
2。 然后我尝试了
select itm,numbr,case when itm=NULL then row_sequence()+1 else row_sequence() end as incr from table;
它抛出错误" FAILED:RuntimeException org.apache.hadoop.hive.ql.metadata.HiveException:有状态表达式不能在CASE"中使用。
请指教。 TIA。
答案 0 :(得分:2)
未经测试但分析功能应该对您有所帮助,因为incr
列的值取决于其他行的值:
WITH tmpincr as (
SELECT
itm
, nmbr
-- get in tmpincr 1 for NULL, 0 for not null
, if(isnull(itm), 1, 0) as tmpincr
FROM tablename
)
SELECT
itm
, nmbr
-- get the sum of tmpincr for all rows before current one when ordered by itm
, SUM(tmpincr) OVER (
ORDER BY nmbr
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) as incr
FROM tmpincr
ORDER BY nmbr
;
答案 1 :(得分:0)
UPDATE table_name
SET incr = Coalesce(itm, 0) + 1
我还没有尝试过这个解决方案,但如果为null则增加1,否则增加数字。 修改它以满足您的需要=)