Popular Searches

Aggregate Sales with Hive SQL

Big DataBeginner
Practice Now

Introduction

A list of paid orders helps a support agent find a record. A store manager needs a different view: How much did we sell on each date? Answering that question combines several rows into a smaller summary. In SQL, this is called aggregation.

You will first calculate one order's amount, then combine all paid orders, and finally produce daily totals. The business rule matters as much as SQL syntax: this lab counts only orders whose status is paid. Pending and refunded orders are excluded; a refund is not subtracted as a negative sale in this simplified dataset. All amounts use one currency, without tax or discounts.

Hive supplies the SQL query layer over stored files. Beeline sends your SQL to the prepared Hive service. A clean six-row table is provided independently for this lab. You should understand simple SELECT, WHERE, and ORDER BY queries; aggregation is introduced here from the beginning. You do not need Java, Python, service installation, or files from another lab. Use the Terminal.

Calculate Each Paid Order's Amount

In this step, you will establish which rows count as sales before adding them together. Each row represents one simplified order containing a single product type. quantity is a whole-number count and unit_price is DECIMAL(10,2), an exact decimal number with two fractional digits. Decimal arithmetic is appropriate for these monetary amounts.

Start in the prepared workspace:

cd /home/labex/project

Inspect the small source file. The first line is a header; the table is already configured to skip it:

cat /home/labex/project/data/orders.csv

WHERE retains paid rows. The multiplication operator * combines two numeric columns within each retained row. AS order_amount gives that calculated result a readable column name, called an alias. It does not add a stored column to the original file.

The following command uses Beeline's connection URL (-u), username (-n), and SQL argument (-e). --silent=true reduces client chatter; --showHeader=false --outputformat=tsv2 produces tab-separated result rows without a header. The shell's > saves output locally, replacing an existing transcript. Quotes keep the whole SQL statement together:

beeline -u 'jdbc:hive2://localhost:10000/default' -n labex --silent=true --showHeader=false --outputformat=tsv2 -e "SELECT order_id, quantity, unit_price, quantity * unit_price AS order_amount FROM retail_aggregation.orders WHERE order_status = 'paid' ORDER BY order_id;" > /home/labex/project/output/order-amounts.tsv
cat /home/labex/project/output/order-amounts.tsv

Read the four result rows as follows; numeric display may include extra trailing zeroes:

Order Quantity Unit price Amount
o1 2 10.00 20.00
o2 1 25.00 25.00
o4 2 25.00 50.00
o6 2 15.00 30.00

o3 and o5 do not contribute. This calculation still returns one row per paid order; it has not yet combined orders.

Combine All Paid Orders into One Total

In this step, you will reduce the four paid rows to one summary row. COUNT(*) counts rows, including rows with missing values in individual columns. SUM(expression) adds non-NULL values of that expression. This prepared dataset has known quantities and prices; in real reporting you would investigate missing prices rather than silently invent zero revenue.

Order count and unit count answer different questions: an order for two notebooks is one order but two units. Run all three measures together:

beeline -u 'jdbc:hive2://localhost:10000/default' -n labex --silent=true --showHeader=false --outputformat=tsv2 -e "SELECT COUNT(*) AS paid_orders, SUM(quantity) AS units_sold, SUM(quantity * unit_price) AS revenue FROM retail_aggregation.orders WHERE order_status = 'paid';" > /home/labex/project/output/paid-totals.tsv
cat /home/labex/project/output/paid-totals.tsv

Expect one result row with 4 paid orders, 7 units, and 125.00 revenue. Check the revenue yourself: 20 + 25 + 50 + 30 = 125. Without GROUP BY, the aggregate functions combine all rows that passed WHERE into one group. The original six source records remain unchanged.

Next, you will split that overall group by date so a manager can compare days.

Build a Daily Sales Summary

In this step, you will produce one row per date. GROUP BY order_date puts retained rows with the same date into a group; each aggregate is calculated separately inside that group. A selected column such as order_date must identify the group, while measures such as revenue aggregate its rows. ORDER BY then sorts the resulting summary rows; grouping alone does not guarantee display order.

Save the query so it can be reviewed and rerun. The following here-document sends the lines between SQL markers into the named file; the quoted opening marker preserves the SQL text literally:

cat > /home/labex/project/queries/daily-sales.sql <<'SQL'
SELECT order_date, COUNT(*) AS paid_orders, SUM(quantity * unit_price) AS revenue
FROM retail_aggregation.orders
WHERE order_status = 'paid'
GROUP BY order_date
ORDER BY order_date;
SQL

Execute that file with -f and inspect its saved result:

beeline -u 'jdbc:hive2://localhost:10000/default' -n labex --silent=true --showHeader=false --outputformat=tsv2 -f /home/labex/project/queries/daily-sales.sql > /home/labex/project/output/daily-sales.tsv
cat /home/labex/project/output/daily-sales.tsv

The result should describe these groups:

Date Paid orders Revenue
2026-10-14 2 45.00
2026-10-15 2 80.00

The two daily amounts add back to 125.00. That reconciliation is a useful check: both queries apply the same paid-order rule, so grouping changes the shape of the answer without changing the overall revenue.

Distinguish Row Filters from Group Filters

In this step, you will use a date condition to select input rows and HAVING to select completed groups. Conceptually, read the query in this order: FROM chooses the table, WHERE selects rows, GROUP BY forms groups, aggregates calculate measures, HAVING selects groups, and ORDER BY sorts the answer.

A date condition belongs in WHERE. DATE '2026-10-15' is an explicit SQL date value. A revenue condition involving SUM(...) belongs in HAVING, because the sum is known only after rows have been grouped. Save a new query for October 15, keeping only date groups with revenue above 50:

cat > /home/labex/project/queries/selected-day.sql <<'SQL'
SELECT order_date, COUNT(*) AS paid_orders, SUM(quantity * unit_price) AS revenue
FROM retail_aggregation.orders
WHERE order_status = 'paid' AND order_date = DATE '2026-10-15'
GROUP BY order_date
HAVING SUM(quantity * unit_price) > 50
ORDER BY order_date;
SQL
beeline -u 'jdbc:hive2://localhost:10000/default' -n labex --silent=true --showHeader=false --outputformat=tsv2 -f /home/labex/project/queries/selected-day.sql > /home/labex/project/output/selected-day.tsv
cat /home/labex/project/output/selected-day.tsv

Expect only October 15, with 2 orders and 80.00. October 14 was excluded before grouping by the date condition; it was not included and then merged into October 15.

Now predict the answer when you remove the date restriction and keep groups whose revenue exceeds 40. Both days qualify: 45 and 80 exceed 40. Save and run that variation:

cat > /home/labex/project/queries/qualifying-days.sql <<'SQL'
SELECT order_date, COUNT(*) AS paid_orders, SUM(quantity * unit_price) AS revenue
FROM retail_aggregation.orders
WHERE order_status = 'paid'
GROUP BY order_date
HAVING SUM(quantity * unit_price) > 40
ORDER BY order_date;
SQL
beeline -u 'jdbc:hive2://localhost:10000/default' -n labex --silent=true --showHeader=false --outputformat=tsv2 -f /home/labex/project/queries/qualifying-days.sql > /home/labex/project/output/qualifying-days.tsv
cat /home/labex/project/output/qualifying-days.tsv

You should see both dates again. Comparing the two queries separates the decisions: WHERE controls which orders enter the calculation; HAVING controls which calculated groups appear. Your original daily-sales.sql still provides the complete paid-sales summary. You are ready to apply the same mapping and reporting steps to a new file independently.

Summary

You defined a paid-sales rule, calculated decimal amounts per order, reconciled whole-dataset and daily aggregates, and distinguished row selection with WHERE from group selection with HAVING. Saved SQL files make each result reproducible and explainable. Next, a new-file challenge lets you combine external-table mapping and daily aggregation without introducing new SQL concepts.