首页 > 解决方案 > HiveQL:将列的所有值除以列的最大值

问题描述

如何将列的所有值除以列的最大值?

例如,假设我有:

id value
1  10
2  20
3  30

我想:

id value
1  0.33333
2  0.66666
3  0.99999

我努力了:

SELECT col_a/MAX(col_a)
FROM db.table

SELECT col_a/(SELECT MAX(col_a) FROM db.table)
FROM db.table

并且两次尝试都失败了,并出现了冗长的错误消息。

当我复制粘贴它时,我能够得到下面第一个答案的代码,但我无法用我自己的表复制它的结果。我试过了:

WITH temp AS (SELECT * FROM mydb.tablenamehere)
SELECT colA/MAX(colA) OVER()
FROM temp;

并且:

USE mydb;
WITH temp AS (SELECT * FROM tablenamehere)
SELECT colA/MAX(colA) OVER()
FROM temp;

但我得到以下两个错误:

FAILED: SemanticException Line 1:28 Table not found 'tablenamehere' in definition of CTE temp [
SELECT * FROM tablenamehere
] used as temp at Line 1:28

标签: hivehiveql

解决方案


使用分析max()

with your_table as ( --use your table instead of this
select stack(3,
1,  10 ,
2,  20 ,
3,  30 ) as (id, value)
)

select id, value/max(value) over() as value 
  from your_table
order by id --remove order if not necessary
; 

回报:

OK
1       0.3333333333333333
2       0.6666666666666666
3       1.0
Time taken: 80.474 seconds, Fetched: 3 row(s)

推荐阅读