Calculate percentage in hive

Requirement

You have marks of all the students of a class with roll number in CSV file. It is needed to calculate the percentage of marks of students in the hive.

Given:

Download the sample CSV file marks which have 7 columns, 1st column is Roll no and other 6 columns are subject1 subject2….subject6.

Solution

Step 1: Loading the sample CSV file into Hive Table

I have a local directory named as “calculate-percentage-in-hive” in path “/root/local_bdp/problems/”,
so I have kept marks.csv file in that path.

You can see sample data in below screenshot:-

Let’s create the HDFS directory using below command:

 hadoop fs -mkdir -p hdfs://sandbox.hortonworks.com:8020/user/root/bdp/problems/cal_per_hive/ip/

As you can see “ip” directory is created for input files.
Now, we can copy the file into HDFS using below command:

 hadoop fs -put /root/local_bdp/problems/calculate-percentage-in-hive/marks.csv hdfs://sandbox.hortonworks.com:8020/user/root/bdp/problems/cal_per_hive/ip/

If you have trouble in the understanding of loading of CSV file into the hive, you can refer here. Use below commands in hive to create an external table:

 CREATE SCHEMA IF NOT EXISTS bdp;
CREATE EXTERNAL TABLE IF NOT EXISTS bdp.hv_per
(roll_no INT,subject1 INT,subject2 INT,subject3 INT,subject4 INT,subject5 INT,subject6 INT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
STORED AS TEXTFILE
LOCATION 'hdfs://sandbox.hortonworks.com:8020/user/root/bdp/problems/cal_per_hive/ip/';

You can skip the above step if the data is already available in hive table.

Step 2: Hive

Now, it’s time to interact with hive CLI.

Enter the below command:-

 hive

It will take you to hive CLI. As we have created a hv_per table in bdp schema which has all 7 columns. Use below command to see whether data is loaded into the table or not:

 Select * FROM bdp.hv_per;

Step 3: Calculation of Percentage

Use below query to calculate the percentage:

 SELECT  roll_no,CAST(subject1+subject2+subject3+subject4+subject5+subject6 AS float)/6.0 AS percentage
FROM bdp.hv_per;

As you can see, first we are summing all subjects and then casting the result of the sum in to float, after that we are dividing it by 6.0. We have assumed that the total marks of each subject are 100. You can change the formula if you wish.

Refer below screenshot, which is the output of the query:

Keep learning. Keep sharing.

If you want to learn how to calculate percentage in spark using scala, click here.

Don’t miss the tutorial on Top Big data courses on Udemy you should Buy

Sharing is caring!

Subscribe to our newsletter
Loading

Leave a Reply