SQL sum field when column values ​​match

The name was difficult to formulate, but the question is quite simple. I was looking for everything here and could not find something for my specific problem, so here it is. I am using Microsoft SQL Server Management Studio 2010.

The table currently looks like this

| Value | Product Name| | 300 | Bike | | 400 | Bike | | 300 | Car | | 300 | Car | 

I need a table to show me the sum of the values ​​in which the product name matches - for example,

  | TOTAL | ProductName | | 700 | Bike | | 600 | Car | 

I tried simple

  SELECT SUM(Value) AS 'Total' ,ProductName FROM TableX 

But the above does not work. As a result, I get the sum of all the values ​​in the column. How can I summarize based on product name match?

Thanks!

+8
sql sum
source share
2 answers
 SELECT SUM(Value) AS 'Total', [Product Name] FROM TableX GROUP BY [Product Name] 

SQL script example

+11
source share

Anytime you use the aggregate function, ( SUM , MIN , MAX ...) with a column in a SELECT , you must use GROUP BY . This is a group function that indicates in which column the population is grouped. Also, any columns that are not part of the aggregate cannot be in your SELECT .

For example, the following syntax is invalid because you specify columns ( col2 ) that are not in your GROUP BY (although MySQL allows this):

 SELECT col1, col2, SUM(col3) FROM table GROUP BY col1 

The solution to your question will be:

 SELECT ProductName, SUM(Value) AS 'Total' FROM TableX GROUP BY ProductName 
+2
source share

All Articles