1

In Hive I have a table with a column as string datatype and it contains set of numbers say marks. So I want to apply some arithmetic operations like addition, so I used split command and it returns array. Bt I can't apply addition to the array I think I need to convert into array to apply any arithmetic operations. I used command followed

select sum(a) from (select split(marks, ':') as a from tbl) b;

And I tried to cast it into array also bt not working giving some error. I tried following commands

select sum(a) from (select cast(split(marks, ':') as a array<int>) from table) b;
select sum(a) from (select cast(b) as array<int> from (select split(marks, ':') as b from tbl) c) d;

Please suggest me the solution for this.. And also how to cast array to array

4
  • Could you please provide your input sample? That way it'll be easy to help you Commented Jun 6, 2018 at 5:29
  • Marks 45:52:56:74 85:65:63:42 63:52:43:68 Marks column as string datatype and table name is tbl Commented Jun 6, 2018 at 6:48
  • You can do CAST(Split(marks,':')[0] AS bigint),CAST(Split(marks,':')[1] AS bigint),CAST(Split(marks,':')[2] AS bigint),CAST(Split(marks,':')[3] AS bigint) Commented Jun 6, 2018 at 6:52
  • Answered the same: stackoverflow.com/a/50333654/2700344 Commented Jun 6, 2018 at 15:04

2 Answers 2

1

You can use this:

select sum(cast(a as int)) from TableName;
Sign up to request clarification or add additional context in comments.

2 Comments

It won't work I think it will give classCastException because a is an array<string> so we can't cast into int..
You can use this: select a, sum(cast(a as int)) as sum_of_marks from TableName lateral view explode (split(marks,':')) t1 AS a
1

You can do something like this, hope this helps

Select 
 sum(a), 
 sum(b), 
 sum(c), 
 sum(d)
From
(Select
  CAST(Split(marks,':')[0] AS bigint) AS a, 
  CAST(Split(marks,':')[1] AS bigint) AS b,
  CAST(Split(marks,':')[2] AS bigint) AS c, 
  CAST(Split(marks,':')[3] AS bigint) AS d
From
Table) split_data
Group by <some column>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.