Search code examples
sql-serversumsql-server-2017

How to get sum of rows where it matches the condition


I am trying to get the sum of the rows where it matches the condition. Suppose you have column a, b and a is consisted of arbitrary integers from 0 to 500.

Let's say there are 5 rows in the table I want to calculate from.

|---------------------|------------------|
|           a         |          b       |
|---------------------|------------------|
|          1          |          1       |
|---------------------|------------------|
|          3          |          4       |
|---------------------|------------------|
|          2          |          6       |
|---------------------|------------------|
|          3          |          8       |
|---------------------|------------------|
|          1          |          9       |
|---------------------|------------------|

I would like to get the sum of rows for each value in column A. The result would be as below.

|---------------------|------------------|
|           a         |        sum       |
|---------------------|------------------|
|          1          |         10       |
|---------------------|------------------|
|          2          |          6       |
|---------------------|------------------|
|          3          |         12       |
|---------------------|------------------|

Thank you for taking the time to read.


Solution

  • Select a, SUM(b) sum From Table
    Group By a