Calculate the sum of column in SQL

Mohammed Imtiyaz Nov 21, 2014

Introduction

In this article we will discuss how to calculate the sum of result query in SQL server.
Suppose you have a table (tbl_product) with columns (productId, productName, price and qty) as follows:

Example 1

productId productName price qty
1 Labtop Bag $ 800 1
2 Network Cable $ 250 1
3 Keyboard $ 300 4
4 Router $ 1100

Let's say you want to calculate the total price of each product (i.e., price of the product X quantity of product), you need to write an SQL Query to achieve this as mentioned below.

SQL Query

SELECT productId, 
     productName, 
     price, 
     qty, 
     price*Qty 'Total' 
 FROM tbl_product

The output for the above mentioned SQL Query will be as follows:

Product Id Product Name Price Qty Total
1 Labtop Bag $ 800 1 $ 800
2 Network Cable $ 250 1 $ 250
3 Keyboard $ 300 4 $ 1200
4 Router 1$ 100 $ 2200

Example 2

Now if you want to calculate the gross total you need to modify the SQL Query as follows:

SQL Query

SELECT productId, 
     productName, 
     price, qty, 
     price*Qty 'Total', 
     SUM(price*Qty) OVER() 'Gross Total' 
 FROM tbl_product

The output for the above mentioned SQL Query will be as follows:

Product Id Product Name Price Qty Total Gross Total
1 Labtop Bag $ 800 1 $ 800 $ 4450
2 Network Cable $ 250 1 $ 250 $ 4450
3 Keyboard $ 300 4 $ 1200 $ 4450
4 Router $ 1100 2 $ 2200 $ 4450

Example 3

Let's assume that we have the table, "tbl_product" as follows

Product Id Product Name Brand Price Qty
1 Labtop Sony $ 800 1
2 Labtop Dell $ 780 2
3 Keyboard Dell $ 40 2
4 Mouse HP $ 15 3
5 Printer HP $ 1150 1

Now, let us assume that we need to calculate the total price of products based on the brand of the product or name of the product

Now, we’ll see how to calculate the total price of products based on the brand of the product

SQL Query

SELECT product_id,
     product_name, 
     product_brand, 
     product_price, 
     qty,  SUM(product_price  * qty) OVER(partition by product_brand) 'Brand wise total'
FROM tbl_product 

The output for the above mentioned SQL Query will be as follows:

Product Id Product Name Brand Price Qty Brand wise total
1 Labtop Sony $ 800 1 $ 800
2 Labtop Dell $ 780  2 $ 1640
3 Keyboard Dell $ 40 2 $ 1640
4 Mouse HP $ 15 3 $ 1195
5 Printer HP $ 1150 1 $ 1195

Now, we’ll see how to calculate the total price of products based on the product name of the product

Note: The 'partition' key works as GROUP BY Clause in the OVER() Clause.

SQL Query

SELECT product_id,
     product_name, 
     product_brand, 
     product_price, 
     qty,  SUM(product_price  * qty) OVER(partition by product_name) 'Name wise total'
FROM tbl_product 

The output for the above mentioned SQL Query will be as follows:

Product Id Product Name Brand Price Qty Brand wise total
1 Labtop Sony $ 800 1 $ 2360
2 Labtop Dell $ 780  2 $ 2360
3 Keyboard Dell $ 40 2 $ 80
4 Mouse HP $ 15 3 $ 45
5 Printer HP $ 1150 1 $ 1150