---
title: "Column Sum in Select Query in SQL"  
description: "Column Sum in Select Query in SQL"  
author: "Anonymous User"  
published: 2013-10-05  
updated: 2013-10-05  
canonical: https://www.mindstick.com/forum/1599/column-sum-in-select-query-in-sql  
category: "mssql server"  
tags: ["mssql server"]  
reading_time: 2 minutes  

---

# Column Sum in Select Query in SQL

I have trouble with [sql server](https://www.mindstick.com/articles/12999/what-is-table-valued-function-in-sql-server) [select query](https://www.mindstick.com/articles/1858/sqlite-select-query). I have following table.

```
ID-----Name----Quantity
```

```
1-------Jhon-----------10
```

```
2-------Jay -----------30
```

```
3-------Nik-----------20
```

```
4-------Carlos----------15
```

```
5-------Rikki-----------10
```

```
6-------Mark-----------30
```

```
7-------Amr-----------40
```

I want to select those record where the [sum](https://www.mindstick.com/forum/159332/how-can-i-use-sum-in-linq) of Quantity < value. For example if I [say](https://answers.mindstick.com/qa/116645/a1-wreckers-reviews-what-do-customers-say) select those record where the Quantity sum <65 then the [output](https://www.mindstick.com/interview/34427/explain-the-output-in-angular) will be

```
ID-----Name----Quantity
```

```
1-------Jhon-----------10
```

```
2-------Jay-----------30
```

```
3-------Nik-----------20
```

because if we include the next record then the sum of Quantity will 75.

I want to create this query. Please help me out.

## Replies

### Reply by Anonymous User

You can simply use a correlated subquery to do so, and it will work fine for both MySQL, and [SQL](https://www.mindstick.com/articles/13115/types-of-keys-in-sql-or-oracle-database) [Server](https://www.mindstick.com/articles/43769/what-is-serverless-architecture-is-it-worth-switching-over). But it is not the best performance wise solution:

```
SELECT
  ID,
  Name,
  Quantity
FROM
(
  SELECT
    t1.ID,
    t1.Name,
    t1.Quantity,
    (SELECT SUM(t2.Quantity)
     FROM tablename AS t2
     WHERE t2.ID <= t1.ID) AS Total
  FROM Tablename AS t1
) AS t
WHERE Total < 65;
```

\

**Output: -**

This will give you:

```
| ID | NAME | QUANTITY |
```

```
------------------------
```

```
|  1 |    Jhon |       10 |
```

```
|  2 |    Jay|       30 |
```

```
|  3 |    Nik|       20 |
```


---

Original Source: https://www.mindstick.com/forum/1599/column-sum-in-select-query-in-sql

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
